The Javascript array filter() creates a new array of elements from an existing array that meets a specified condition.
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.
currentValue
is the element currently being executed – required.index
the index of the element – optional.arr
is the array that is currently being processed – optional.thisValue
is an argument passed to be used as the this value in the callback – optionalconst filteredArray = originalArray.filter(callbackFunction(currentValue, index, arr), thisValue);
The first example is quite simple, suppose we have an array of several ages. And that we need to create a new array only with ages over or equal to 18. Simple isn’t it?
The syntax gets even cleaner when we use the Arrow Function syntax.
const ages = [-243, -132, 112, 40, -96];
const filtered = ages.filter(number => number > 0);
console.log(filtered);
// [112, 40]
For our second case, we have an Array of Objects with several products that we need to filter according to the user preference. In this case, price.
We need to interact over this array to find all those products that match with our condition. Thera are four products inside this array, and each one is an Object, we need to interact over the objects as well, 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 above 200 ‘monies’ will be inserted into the new array and you can then display the result of the filter 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" }
]
*/
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 it 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 }, { id: 0 }, { id: 3 }, { id: 12.2 } ]
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 Javascript array filter function 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 ]
Bookmarked!, I like it!
Great information
Leave a Reply