The filter()
Array method creates a new array with elements that fall under a given criteria from an existing array.
In this article, you will learn about the filter()
Array method.
If you would like to follow along with this article, you will need:
filter()
on an Array of NumbersThe syntax for filter()
resembles:
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 returned to the new array.
Consider this example array of numbers:
var numbers = [1, 3, 6, 8, 11];
Then apply a filter()
to return all numbers that are greater than 7
:
var greaterThanSeven = numbers.filter(function(number) {
return number > 7;
});
console.log(greaterThanSeven);
This code will generate a new filtered array:
output[8, 11]
An array with two values greater than 7 is returned.
filter()
on an Array of ObjectsA common use case of filter()
is with an array of objects through their properties.
Consider this example array of creature
objects:
var creatures = [
{name: "Shark", habitat: "Ocean"},
{name: "Whale", habitat: "Ocean"},
{name: "Lion", habitat: "Savanna"},
{name: "Monkey", habitat: "Jungle"}
];
Then apply a filter()
to return all creatures with a habitat
that is equal to Ocean
:
var aquaticCreatures = creatures.filter(function(creature) {
return creature.habitat == "Ocean";
});
console.log(aquaticCreatures);
This code will generate a new filtered array:
Output[ {name: "Shark", habitat: "Ocean"}, {name: "Whale", habitat: "Ocean"} ]
An array with the two creatures that have a habitat in the “Ocean” is returned.
In this article, you learned about the filter()
Array method.
For more details, consult the MDN Reference on filter()
.
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()
.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
Sign up for Infrastructure as a Newsletter.
Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.