Skip to content

JavaScript find all matches in array | Example

  • by

Use JavaScript filter() and indexOf() method to find all matches in array. Array.filter returns a new array containing all matching elements, [] if it matches nothing.

JavaScript finds all matches in the array

Simple example code use indexOf which is returning the position of the matching string, or -1 if it matches nothing.

<!DOCTYPE html>
<html>
<body>
  <script>
    let arr = [
    { name:"string 1", arrayValue:"1", other: "One" },
    { name:"string 2", arrayValue:"2", other: "Two" },
    { name:"string 3", arrayValue:"2", other: "Three" },
    { name:"string 4", arrayValue:"4", other: "Four" },
    { name:"string 5", arrayValue:"4", other: "Five" },
    ];
    const items = arr.filter(item => item.arrayValue.indexOf('4') !== -1);

    console.log(items)

  </script>
</body>
</html>

Output:

JavaScript find all matches in array

Another simple 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]

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 }]

Do comment if you have any doubts or suggestions on this Js Array topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading