Skip to content

Searching in Arrays

JavaScript gives arrays two kinds of search method. includes() and indexOf() look for one exact value. some(), find() and findIndex() take a callback, which is a function that tests each item, so they can search on any condition.

includes() returns true or false. indexOf() returns the index of the first match, or -1 when there is none:

const books = ['Dune', 'Emma', 'Ulysses', 'Beloved', 'Middlemarch'];
console.log(books.includes('Emma'));
console.log(books.includes('emma'));
console.log(books.indexOf('Ulysses'));
console.log(books.indexOf('Persuasion'));

This prints:

true
false
2
-1

The match must be exact, so the search is case-sensitive. Use includes() when the answer is yes or no, and indexOf() when you need the position, for example to pass to splice(). Both accept a second argument, which is the index to start from.

The two methods differ in one case. includes() finds NaN, but indexOf() does not, because indexOf() uses strict equality and NaN is not equal to itself:

const readings = [12.5, NaN, 14];
console.log(readings.includes(NaN));
console.log(readings.indexOf(NaN));

This prints:

true
-1

some() calls its callback on each item until the callback returns a truthy value, and then returns true. find() works the same way but returns the matching item itself, and findIndex() returns its index:

const books = ['Dune', 'Emma', 'Ulysses', 'Beloved', 'Middlemarch'];
const hasLongTitle = books.some((title) => title.length > 10);
console.log(hasLongTitle);
const startsWithB = books.find((title) => title.startsWith('B'));
console.log(startsWithB);
const shortIndex = books.findIndex((title) => title.length < 5);
console.log(shortIndex);
console.log(books.find((title) => title.startsWith('Z')));

This prints:

true
Beloved
0
undefined

When nothing matches, some() returns false, find() returns undefined and findIndex() returns -1. The callback should return a boolean. Returning the item itself, as in find((title) => title.length > 5 && title), appears to work but fails for items that are falsy, such as 0 or an empty string.

Each of these methods stops at the first match, so it does no more work than it needs to. Array some and Array find and findIndex cover them in more detail.

findLast() and findLastIndex(), added in ES2023, search from the last item backwards:

const temps = [11, 17, 9, 21, 14, 23, 8];
console.log(temps.find((t) => t > 20));
console.log(temps.findLast((t) => t > 20));
console.log(temps.findLastIndex((t) => t < 10));

This prints:

21
23
6

Searching from the end is useful for the most recent entry in a log or a list kept in date order. Finding Matches in Arrays applies these methods to arrays of objects, where a plain value search no longer works.

Steve Griffith covers this topic in his video Searching in Arrays.