.filter() explained simply

Definition

.filter(callbackFn) in JavaScript is a higher order function (a function that either takes in another function as an argument or that returns another function). .filter is an Array method that allows you to loop over each element of array A and apply a callback function that you specify on each element. The callback function for each element should return a boolean that will determine if this element should be included in the new resulting array B.

Get Started

We’ll start with the following array:

const arr = [1,2,3,4,5,6,7,8,9,10];

Let’s say that we don’t want our array to have even numbers. Let’s filter out the odd numbers. How would we do this? I suppose one way we could do this is by using a for-of loop:

const arr = [1,2,3,4,5,6,7,8,9,10];
const newArr = [] ;

for(let num of arr)
{
    if(num % 2 == 0)
        newArr.push(num);
}
console.log(newArr); // [2,4,6,8,10]
		

But this is not necessary. We can simply use .filter(callbackFn) to loop over each element of arr and apply a callback function to every element that will determine if the current element should be included in the resulting array.

const arr = [1,2,3,4,5,6,7,8,9,10];
const newArr = arr.filter((num) => {
    if(num % 2 == 0)
        return true;
});

This is how we use .filter. We take the array we want to filter (arr) and call arr.filter(callbackFn). .filter takes in a callback function as an argument. .filter will start from the beginning of the original array and apply this callback function to every element. The num parameter in the callback stands for the current element from the original array (arr). If the callback returns true then that element will be included in the resulting array. If the callback returns false, the element will not be included in the resulting array.

So, for each element we say does num % 2 == 0 (number is even)? Yes ? Then return true and include this element in the resulting array. No ? Then don’t include the element in the resulting array.

NOTICE:.filter DOES NOT modify the original array. It creates a new array. That means that this code will not do anything useful:

const arr = [1,2,3,4,5,6,7,8,9,10];
arr.filter((num) => {
    if(num % 2 == 0)
        return true;
});

console.log(arr) // [1,2,3,4,5,6,7,8,9,10] - Bad! .filter does not modify the original array!

Also, we can take advantage of implicit return to make our .filter implementation cleaner and easier to read:

const arr = [1,2,3,4,5,6,7,8,9,10];
const newArr = arr.filter(num => num % 2 == 0);
console.log(newArr) // [2, 4, 6, 8, 10]

Summary

.filter(callbackFn) in JavaScript is a higher order function for arrays that allows you to loop over each element of array A and apply a callback function that you specify on each element. The callback function for each element should return a boolean that will determine if this element should be included in the new resulting array B.

If this article was helpful, tweet it!