Searching arrays: find, includes, some and every

An array answers two kinds of question: where is this value, and is there any value that passes this test. The first kind is indexOf, lastIndexOf and includes, which compare with === and need the value itself. The second is find, findIndex and the pair some and every, which call a JavaScript function for each item and read its answer.

The difference matters for a list of objects, where the value a caller holds is often a copy and not the item in the array. This lesson shows the results of both families, including the cases where nothing is found, and ends with the reason a lookup by a field is written as a predicate or moved into a Map.

indexOf, lastIndexOf and includes

indexOf returns the position of the first match and lastIndexOf the position of the last one, and both answer -1 when there is none. includes answers the yes or no question directly, and it is the one that finds NaN, because it compares with the same rule as the SameValueZero check that a Set uses.

const letters = ['a', 'b', 'c', 'b']; console.log('indexOf b:', letters.indexOf('b')); console.log('lastIndexOf b:', letters.lastIndexOf('b')); console.log('indexOf a missing value:', letters.indexOf('z')); console.log('includes c:', letters.includes('c')); console.log('includes z:', letters.includes('z')); console.log('NaN with indexOf:', [NaN].indexOf(NaN)); console.log('NaN with includes:', [NaN].includes(NaN)); console.log('a number and its text:', ['1'].indexOf(1));

node identity.js

indexOf b: 1
lastIndexOf b: 3
indexOf a missing value: -1
includes c: true
includes z: false
NaN with indexOf: -1
NaN with includes: true
a number and its text: -1

The two positions of b show the difference between the two index methods, and -1 is the answer that a caller has to test for, since it is a number and not false. NaN is the one value that === never matches, not even itself, so indexOf misses it while includes finds it. The last line is the other everyday trap: the number 1 and the string "1" are different values and no search by value will mix them.

find and findIndex

find takes a predicate and returns the first item it accepts, or undefined. findIndex returns the position of that item or -1, and findLast and findLastIndex walk the array from the end. The predicate receives the value, the index and the array, so a search can depend on the position as well.

const people = [ { name: 'ada', year: 1815 }, { name: 'alan', year: 1912 }, { name: 'grace', year: 1906 }, ]; const after1900 = (person) => person.year > 1900; console.log('find:', people.find(after1900).name); console.log('findIndex:', people.findIndex(after1900)); console.log('findLast:', people.findLast(after1900).name); console.log('findLastIndex:', people.findLastIndex(after1900)); console.log('find with no match:', people.find((person) => person.year > 2000)); console.log('findIndex with no match:', people.findIndex((person) => person.year > 2000));

node find.js

find: alan
findIndex: 1
findLast: grace
findLastIndex: 2
find with no match: undefined
findIndex with no match: -1

Two people were born after 1900, so the forward search finds the first and the backward search the last, and the index methods agree with them. The two lines without a match are the important ones: find gives undefined and findIndex gives -1, so a caller that reads found.name has to know which one it called. A test such as index !== -1 or a check for undefined is what turns the search into a decision.

some and every

some answers whether at least one item passes the predicate, and every whether all of them do. Neither returns a value from the array, and both stop as soon as the answer is settled: some at the first true and every at the first false. The program counts the calls to make the stopping visible.

const numbers = [2, 4, 6]; console.log('some odd:', numbers.some((n) => n % 2 === 1)); console.log('some even:', numbers.some((n) => n % 2 === 0)); console.log('every even:', numbers.every((n) => n % 2 === 0)); console.log('every on an empty array:', [].every((n) => n > 0)); console.log('some on an empty array:', [].some((n) => n > 0)); let calls = 0; [1, 2, 3].some((n) => { calls += 1; return n === 2; }); console.log('calls until some finds one:', calls); calls = 0; [1, 2, 3].every((n) => { calls += 1; return n < 2; }); console.log('calls until every fails:', calls);

node someevery.js

some odd: false
some even: true
every even: true
every on an empty array: true
some on an empty array: false
calls until some finds one: 2
calls until every fails: 2

The two empty-array answers follow from logic rather than from a special case: there is no item that fails, so every is true, and there is no item that passes, so some is false. Two calls each show where the loops stopped: the second item was the one some wanted, and the second item was the one that broke every. The remaining items were never visited, which matters when the predicate is expensive.

Searching a list of objects

The index methods compare with ===, and for objects that means the same object, not an equal one. A record built from a form or read from JSON is a new object even when every field matches, so includes says no while some with a predicate says yes. The program shows both answers on the same list.

const users = [ { id: 1, name: 'ada' }, { id: 2, name: 'alan' }, ]; const found = users.find((user) => user.id === 2); console.log('found by a field:', found.name); console.log('the same object is in the array:', users.includes(found)); console.log('a look-alike is not:', users.includes({ id: 2, name: 'alan' })); console.log('a predicate accepts the look-alike:', users.some((user) => user.id === 2)); const byId = new Map(users.map((user) => [user.id, user])); console.log('a Map finds the same object:', byId.get(2) === found); console.log('an array of pairs:', JSON.stringify([...byId]));

node which.js

found by a field: alan
the same object is in the array: true
a look-alike is not: false
a predicate accepts the look-alike: true
a Map finds the same object: true
an array of pairs: [[1,{"id":1,"name":"ada"}],[2,{"id":2,"name":"alan"}]]

The item that find returned is the item that is in the array, so includes accepts it; the object written out by hand is another object with the same fields and is refused. The predicate does not care about identity, since it reads the field itself. The last two lines are the other answer for a list that is searched often: a Map built once from the records finds an object by key without walking the array at all, and memoization uses the same structure for results.

Exercises

  1. Search for undefined with indexOf and with includes in an array that holds one. Do the two agree?
  2. Give find in find.js a predicate that matches nobody. Which value does findLast return then?
  3. Count the calls of every on [2, 4, 6] with a predicate that is always true. How many calls are made?
  4. Replace users.includes(found) with a comparison of the two objects through JSON.stringify. Which of the two answers flips?
  5. Build the Map in which.js from user.name instead of user.id and look up alan. Which line of the output changes?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does ["a", "b"].indexOf("b") return?

    Answer

    1

    The position counts from zero, so the second item is at index 1.

  2. What does ["a"].indexOf("z") return?

    Answer

    -1

    The index methods report a value that is not there with -1, which a caller has to test for.

  3. Which method finds NaN in an array?

    Answer

    includes

    includes compares with SameValueZero, which treats NaN as equal to itself, while === does not.

  4. What does this program print? console.log([1, 2, 3].find((n) => n > 5));

    Answer

    undefined

    find returns the item, and with no match there is no item, so the answer is undefined.

  5. What does this program print? console.log([1, 2, 3].findIndex((n) => n > 5));

    Answer

    -1

    findIndex returns a position, and -1 is the position that means no match.

  6. What does [].every((n) => n > 0) return?

    Answer

    true

    There is no item that fails the predicate, so every is true on an empty array.

  7. What does this program print? let calls = 0; [1, 2, 3].some((n) => { calls += 1; return n > 1; }); console.log(calls);

    Answer

    2

    The predicate is called for 1 and then for 2, which passes, and some stops there.

  8. What does this program print? const a = [{ id: 1 }]; const b = { id: 1 }; console.log(a.includes(b), a.some((x) => x.id === 1));

    Answer

    false true

    includes compares object identity, while the predicate reads a field and finds a match.

  9. Which search returns the item itself rather than a position or a yes or no?

    Answer

    find

    find gives the item, or undefined; the other three give a position or a boolean.

  10. Why can a list of objects be searched faster with a Map than with find?

    Answer

    The Map is built once and each lookup does not walk the array

    find walks until a predicate accepts an item, while a Map goes to the key directly.

The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev

Banner image