“filter” function in JavaScript


“filter” function is another function which is used quite a lot in JS applications. It is defined on the prototype of Array class.

Array.prototype.filter

It returns a new array with elements for which a callback function returns a truthy value. In other words, any element which passes the test will be included in the new array.

Syntax

filter(callbackFn, thisArg)
  • callbackFn – function which returns a truthy or falsy value when testing an array element.
    • callbackFn(element, index, array)
      • element – current element of the array on which the callback is executed.
      • index – Optional – index of the current element which is operated on.
      • array – Optional – original array on which filter function is called upon.
  • thisArg – Optional – value to be used as this while calling the callbackFn.

Examples

    const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    const evenNumbers = numbers.filter(x => x % 2 === 0);
    console.log(evenNumbers);
[ 2, 4, 6, 8, 10 ]
    const friends = [
        { name: 'John', netWorth: 43 },
        { name: 'Mike', netWorth: 78 },
        { name: 'Brad', netWorth: 56 },
        { name: 'Ashutosh', netWorth: 65 },
    ];
    const richFriends = friends.filter(x => x.netWorth > 58);
    console.log(richFriends);
[ { name: 'Mike', netWorth: 78 }, { name: 'Ashutosh', netWorth: 65 } ]

Can we write our own “filter” function?

Like polyfills for many other functions, we can write a polyfill for “filter” function as well. Let’s give it a shot.

    Array.prototype.myFilter = function (callbackFn, thisArg) {
        const newArray = [];

        for (let i = 0; i < this.length; i++) {
            const returnValue = callbackFn.call(thisArg, this[i], i, this);

            if (returnValue) {
                newArray.push(this[i]);
            }
        }

        return newArray;
    }
    const animals = [
        { name: 'Cat', canFly: false },
        { name: 'Sparrow', canFly: true },
        { name: 'Lion', canFly: false },
        { name: 'Eagle', canFly: true },
        { name: 'Dog', canFly: false },
        { name: 'Bat', canFly: true },
    ];
    const flyingAnimals = animals.myFilter(x => x.canFly);
    console.log(flyingAnimals);
[
  { name: 'Sparrow', canFly: true },
  { name: 'Eagle', canFly: true },
  { name: 'Bat', canFly: true }
]

Explanation

Let’s understand the above code step by step.

  1. Define a new function on prototype of Array class. We are doing this because we want our function to be available on arrays rather taking them as argument.
  2. Create a new array.
  3. Iterate over the elements of the calling array and test the return value after executing the callbackFn. If the return value is truthy, add the element to the new array.
  4. Return the new array.

References

  1. Mozilla Developer Network (MDN)