Last week, we looked at JavaScript arrays in detail and how to use them to store multiple values in a single variable. Today, you'll learn a useful trick to find all matching items in an array by using the Array.filter() method.

The Array.filter() method creates a new array by iterating over all elements of an array and returns those that pass a certain condition as an array.

The callback function passed as an argument takes in up to three optional parameters. The first is the current element in the iteration, the second is the index of the current item in the array, and the third is the array itself.

In the callback body, you can test if the current item matches what you're looking for, and return a boolean (true or false) accordingly.

Here is an example:

const values = [15, 45, 22, 19, 55, 62, 78];

// find all values > 25
const greaterThan25 = values.filter(item => {
    return item > 25;
});

// find all values < 25
const lessThan25 = values.filter(item => item < 25);

console.log(greaterThan25);
// [45, 55, 62, 78]

console.log(lessThan25);
// [15, 22, 19]

The Array.filter() method is not just limited to primitive arrays. You can even use it to filter an array of objects as shown in the following example:

const users = [
    {
        name: 'John Deo',
        age: 35
    },
    {
        name: 'Emma Kel',
        age: 24
    }
    ,
    {
        name: 'Kristy Adam',
        age: 42
    }
];

// find all users older than 40 years
const filteredUsers = users.filter(user => {
    return user.age >= 40;
});

console.log(filteredUsers);
// [{ name: 'Kristy Adam', age: 42 }]

The Array.filter() filter works in all modern browsers, and Internet Explorer 9 and above. However, you can use a polyfill to support IE6 and higher.

Take a look at this guide to learn more about JavaScript arrays and their methods.

✌️ Like this article? Follow @attacomsian on Twitter. You can also follow me on LinkedIn and DEV. Subscribe to RSS Feed.

👋 If you enjoy reading my articles and want to support me to continue creating free tutorials, Buy me a coffee (cost $5) .

Need help to launch a new product? I am available for contract work. Hire me to accomplish your business goals with engineering and design.