JavaScript Array.filter() and Array.find()

26 August 2022

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.

let numbers = [5, 10, 15, 20, 25];
let underTwenty = numbers.filter(number => {
    return number < 20;
});
console.log(underTwenty);
Output
[5, 10, 15]

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.

let cars = [
    {make: "Ferrari", country: "Italy"},
    {make: "Lamborghini", country: "Italy"},
    {make: "McClaren", country: "Britain"},
    {make: "Porsche", country: "Germany"},
];

let italianCars = cars.filter(car => {
    return car.country == "Italy";
});
console.log(italianCars);
Output
[
    {make: 'Ferrari', country: 'Italy'},
    {make: 'Lamborghini', country: '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.

let cars = [
    {make: "Ferrari", country: "Italy"},
    {make: "Lamborghini", country: "Italy"},
    {make: "McClaren", country: "Britain"},
    {make: "Porsche", country: "Germany"},
];

let italianCars = cars.filter(car => {
    return car.country == "Italy";
});
console.log(italianCars);
Output
[
    {make: 'Ferrari', country: 'Italy'}
]

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.