JavaScript Array filter() Demystified: Tips and Examples

Javascript

The Javascript Array filter() method creates a new array of elements from an existing array that meets a specified condition.

In this post we will tell you everything you need to know about the Javascript Array filter() method, we will detail giving several examples of how to use the method. It will be a very complete analysis, follow.

Description of the Javascript method Array filter()

The filter() method once calls a provided callback function for each array element and builds a new array with all values for which the callback returns a truthy value.

The Javascript Array filter() method follows this specification:

  • The callback function is called only for array indexes that have values.
  • Array elements that do not pass the callback test are not included in the new array.
  • Array.filter() does not modify the original array.

The syntax of the filter() method receives 2 parameters, but only one is mandatory.

let novoArray = originalArray.filter(funcaoCallback(currentValue[, index, [array]])[, thisArg])
  • callbackFunction – Required
  • thisArg – Optional

Let’s break down the method, and find out what each parameter represents.

Javascript Array Filter: callback function

callbackFunction is the function, to test each element of the array. This function is expected to return a boolean value.

The function must return true to keep the element, otherwise false, receiving three arguments:

  • currentValue – Required
  • index – Optional
  • array – Optional
const arrayOriginal = [1, 2, 3, 4];

funcaoCallback = function () {
    
}

const novoArray = originalArray.filter(funcaoCallback);

Javascript Array Filter: currentValue

currentValue is the element that is being processed during the current iteration. The array filter() iterates the originalArray through a loop that passes through all elements of the Array. Then during this run, the currentValue parameter will be each of the values of the originalArray.

In the example below I put a console.log() inside our callbackFucntion() function that is now receiving our currentValue parameter and it prints exactly all the elements of our originalArray

const arrayOriginal = [1, 2, 3, 4];

funcaoCallback = function (currentValue) {
    console.log(currentValue);
}

const novoArray = originalArray.filter(funcaoCallback);

/*
1
2
3
4
[]
*/

Javascript Array Filter: index

index is the index of the element that is being checked during the current iteration. In Javascript, the arrays start at index 0.

Each element of our originalArray can be obtained through syntax:

console.log(arrayOriginal[0]); // 1
console.log(arrayOriginal[1]); // 2
console.log(arrayOriginal[2]); // 3
console.log(arrayOriginal[3]); // 4

The number within the [] brackets is the index of each array element. In the filter() method it represents the same values, as you can see in the example below when I put console.log() to print the parameters.

const arrayOriginal = [1, 2, 3, 4];
const novoArray = arrayOriginal.filter(currentValue => console.log(currentValue));
console.log(novoArray); 

// 1 2 3 4 []

Javascript Array Filter: array

array is for our examples the originalArray. But in general it represents the array in which you are calling the filter method.

So understand that if we call our filter() method to another array, that parameter will be the array that the filter method was called.

Going back to our original example, we will have the following result if we use console.log() within our Callbackfunction. Which is exactly the result of the first iteration in the example above.

const arrayOriginal = [1, 2, 3, 4];

funcaoCallback = function (currentValue, index, array) {
    console.log(array);
}

const novoArray = arrayOriginal.filter(funcaoCallback);

/*
[ 1, 2, 3, 4 ]
[ 1, 2, 3, 4 ]
[ 1, 2, 3, 4 ]
[ 1, 2, 3, 4 ]
*/

Javascript Array Filter: thisArg

thisArg is the value to be used as this during the execution of the Callbackfunction. The argument this still causes a lot of confusion among some developers. But it’s not in the scope of this post to explain this argument. I strongly recommend you to visit this link if you want to go deeper into the this argument.

One way we can use thisArg as an initial value for our function for example.

const arrayOriginal = [1, 2, 3, 4];

funcaoCallback = function (currentValue, index, array) {
    console.log(this);
}

const thisArg = 10;
const novoArray = arrayOriginal.filter(funcaoCallback, thisArg);

/*
[Number: 10]
[Number: 10]
[Number: 10]
[Number: 10]
 */

I believe it has become clear what each parameter of the filter method does and what the parameters of the callbackFunction are.

Let’s now move on to examples of how to use the method in the best way.

Javascript Array Filter: Examples

The filter() method has many useful applications, I will list here, 5 of the most common examples that can be adapted in a wide variety of situations.

1 – Filter method with Arrow Function

Arrow functions were entered in ES6. It is nothing more than a syntactically compact alternative to a regular function expression.

All the examples I showed so far could have been written in this syntax, but I believe that the “old” syntax is easier to understand. And in the end, for our examples it makes no difference which syntax you choose.

So let’s transform one of our examples with the Arrow Function syntax. I’ll follow that pattern for all the following examples.

If the function has only one condition, and the condition returns a value, you can remove the {} curly braces and the return keyword:

const arrayOriginal = [1, 2, 3, 4];
const novoArray = arrayOriginal.filter(currentValue => console.log(currentValue));
console.log(novoArray);

/* 
1
2
3
4
[]
*/

2 – Filtering an Array of numbers

The second example is quite simple, suppose we have an array with several numbers, which can be coordinates or id numbers. We need to filter out only the positive numbers from that array.

const ages = [-243, -132, 112, 40, -96];

const filtered = ages.filter(number => number > 0);

console.log(filtered);

// [112, 40]

3 – Filtering an Array of objects

For our third case, we have an Array with several products that we need to filter according to the user preference, in this case, price.

We need to interact on this set to find all the products that match our condition. There are four products within this array, and each one is an object.

We need to interact on the objects too, if you don’t know how to do it, just check this post where a talk about 3 Powerful Ways to Access Properties in Javascript Objects and How to iterate an Object using loops as well.

Any item over $200 must be included within the new array and then you can display the result for the user.

const products = [
    { productName: "Television", price: "1000" },
    { productName: "Pendrive", price: "200" },
    { productName: "Camera", price: "450" },
    { productName: "Mouse", price: "120" }
];

const filtered = products.filter((item) => {
    return item.price > 200;
});

console.log(filtered);

/*
[
    { productName: "Television", price: "1000" },
    { productName: "Camera", price: "450" }
]
*/

4 – Filtering wrong values in an array of Objects

Let’s say that at the time of updating some records in the database the Ids were corrupted by some other piece of code. The goal here is to filter out the wrong id’s.

For this example I established 3 different conditions for a valid Id. using the Javascript array filter() was easy to create a new array with the correct id’s.

const arr = [
    { id: 15 }, { id: -1 }, { id: 0 }, { id: 3 },
    { id: '12' }, { id: null }, { id: NaN }, { id: 'undefined' }
];

const filtered = arr.filter(obj =>
    obj.id !== undefined
    && typeof (obj.id) === 'number'
    && obj.id >= 0
);
console.log(filtered);
//{ id: 15 }, Object { id: 0 }, Object { id: 3 }

5 – Filtering repeated values in an array

Another very common situation is to remove repeated values from an array. To do this it was necessary to use the second parameter of the filter() method to be able to access the index of the current element being processed.

const arr = ["a", 2, "c", 4, "a", 2, 2, 5, "c"];

const filtered = arr.filter((item, index) => arr.indexOf(item) === index);

console.log(filtered);

//[ 'a', 2, 'c', 4, 5 ]

Bottom Line

As we have seen, Javascript Array filter(), is a very useful method. You can link this method with other Javascript methods and create an extremely powerful function.

If you liked the post, don’t forget to leave a comment and subscribe to receive all the news!

See you next time!

Leave a Reply

Your email address will not be published. Required fields are marked *

0 Comments