• 0

Implement filter in javascript

Predicating Arrays

Filtering also key method for manipulating collections. We iterate over the array and add an item to the new array if it passes the test.

  • We will be solving a problem using Array.prototype.forEach().
  • We will define Array.prototype.filter() using Array.prototype.forEach().
  • We will solve the same problem using Array.prototype.filter()

This post is a follow up post of the
- Getting started Functional Programming in JavaScript. I would recommend reading that post first.

Problem

Filter only those videos with a rating of 5.0

Let's solve with Array.prototype.forEach()


Do notice that the array projections have two operations in common:

  • Traversing the source array
  • If an item passes the test then add an item to collection

We can abstract these common operations in Array.prototype.filter()


Implement Array.prototype.filter() using Array.prototype.forEach()



Lets solve with Array.prtotype.filter()


Key Learnings

  • Predicate methods iterates over array and creates a new array of elements which passes the test
  • Array.prototype.filter() allows you to specify the test

Further Reading