Introduction
The filter()
Array method creates a new array with elements that fall under a given criteria from an existing array:
var numbers = [1, 3, 6, 8, 11];
var lucky = numbers.filter(function(number) {
return number > 7;
});
// [ 8, 11 ]
The example above takes the numbers
array and returns a new filtered array with only those values that are greater than seven.
Filter syntax
var newArray = array.filter(function(item) {
return condition;
});
The item argument is a reference to the current element in the array as filter() checks it against the condition. This is useful for accessing properties, in the case of objects.
If the current item passes the condition, it gets sent to the new array.
Filtering an array of objects
A common use case of .filter() is with an array of objects through their properties:
var heroes = [
{name: “Batman”, franchise: “DC”},
{name: “Ironman”, franchise: “Marvel”},
{name: “Thor”, franchise: “Marvel”},
{name: “Superman”, franchise: “DC”}
];
var marvelHeroes = heroes.filter(function(hero) {
return hero.franchise == “Marvel”;
});
// [ {name: “Ironman”, franchise: “Marvel”}, {name: “Thor”, franchise: “Marvel”} ]
Additional Resources
For more details on filter()
see MDN Reference.
Filter is only one of several iteration methods on Arrays in JavaScript, read How To Use Array Iteration Methods in JavaScript to learn about the other methods like map()
and reduce()
.