Searching an array

suggest change

Use Array.prototype.find() to retrieve the first element that satisfies a predicate:

const people = [
  { name: 'Bob' },
  { name: 'John' },
];

const bob = people.find(person => person.name === 'Bob');

The result is undefined when no element matches. Use some() when only a boolean is needed, or includes() when checking for a primitive value directly.

A for...of loop is useful when the search requires more control:

for (const person of people) {
  if (person.name === 'Bob') {
    console.log(person);
    break;
  }
}

Finding an index

findIndex() returns the index of the first matching element, or -1 when no element matches:

const records = [
  { value: 1 },
  { value: 2 },
  { value: 3 },
  { value: 4 },
  { value: 5 },
];

const foundIndex = records.findIndex(record => record.value === 3); // 2
const missingIndex = records.findIndex(record => record.value === 12); // -1

Use findLast() or findLastIndex() when searching from the end of an array.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents