How to find matching items in an array using JavaScript

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 me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.