JavaScript Array.filter() and Array.find()
After learning how to iterate through items in an array using Array.map()
, there are other useful functions which make it easy to use and manipulate data in an array. We’ll look at filtering and finding items in an array.
Array.filter()
The Array.filter() function creates a copy of an array and looks for items that match a given parameter.
In the example above the Array.filter()
function returns a copy of the numbers
array which contains only items that are less than 20.
It’s also possible to filter on an array of objects to return any item that has a value that matches a particular condition. In the case below we’re outputting all the objects from the cars
array that have a country
value of Italy
.
Array.find()
The Array.find()
function is similar to Array.filter()
, however it will only return the first item that matches the given condition.
If we re-use the cars array from earlier but replace .filter()
with .find()
, we will have just one item stored in the italianCars
variable.
Additional parameters
As with the Array.map()
function, there are additional parameters that can be passed into the function to get the index
of the element
and the initial array. These parameters are rarely used with Array.filter()
or Array.find()
but there are situations where they may be useful.