How to find elements in an array in JavaScript

· Category: JavaScript

Short answer

Use find and findIndex for predicate-based searches, includes and indexOf for primitive values, and some/every for boolean checks against conditions.

Steps

  1. Find an object by property: javascript const user = users.find(u => u.id === 42);
  2. Get its index: javascript const idx = users.findIndex(u => u.id === 42);
  3. Check presence: javascript [1, 2, 3].includes(2); // true [1, 2, 3].indexOf(2); // 1
  4. Check conditions: javascript users.some(u => u.active); // at least one active users.every(u => u.active); // all active

Tips

  • find returns undefined if nothing matches; guard against it.
  • includes uses SameValueZero equality, so it finds NaN correctly.

Common issues

  • Using indexOf with objects returns -1 because it compares by reference, not content.
  • find and findIndex stop at the first match; for all matches, use filter.