Searching Through Object Arrays in JavaScript

- 3 minutes read

In JavaScript, arrays are often used to store objects.

Because arrays are technically objects themselves, they have methods.

We can use these methods to easily search through our object arrays, among other things.

Link to this section Searching by key and value

This is the simplest approach I am aware of:

const find = (array, key, value) => {
    return array.indexOf(array.find((e) => e[key] === value));
};

This find() function accepts three parameters:

The function returns an integer, and iterates through each object in the array (unless a match is found before the end has been reached).

If a match is found, the index of the first match will be returned.

And if a match is not found, -1 will be returned.

Link to this section Example usage

const fruits = [
    {
        color: `red`,
        name: `apple`,
    },
    {
        color: `blue`,
        name: `blueberry`,
    },
    {
        color: `yellow`,
        name: `lemon`,
    }
];

// The index of the first match, if any, where the color is blue:
const index = find(fruits, `color`, `blue`);

if (index !== -1) {
    // Print the match to the console:
    console.log(fruits[index]);
} else {
    // If "-1" has been returned, then no match has been found:
    console.log(`Match not found!`);
}

Anyway, the above snippet will output the blueberry object to the console:

{
    color: `blue`,
    name: `blueberry`,
}

Link to this section The one-liner alternative

We can also write a shorter version of the same function in just one line:

const find = (arr, key, val) => arr.indexOf(arr.find((e) => e[key] === val));

Link to this section Returning all matching indexes

But what if you want to find all of the matching objects in an array, and not just the first match?

Well, we can create a findAll() function that continues iterating until the end of the array, even if a match has already been found:

const findAll = (array, key, value) => {
    let matches = [];
    array.forEach((item) => {
        if (item[key] === value) {
            matches.push(array.indexOf(item));
        }
    });
    return matches;
};

The usage of findAll() is quite similar to our find() function.

However, instead of an integer, findAll() returns an array.

The array will contain all of the matching indexes, and it will be empty if no matches are found.

Link to this section Conclusion

I hope this approach helped you search through your object arrays more efficiently!

Thanks for reading.