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
- Find an object by property:
javascript const user = users.find(u => u.id === 42); - Get its index:
javascript const idx = users.findIndex(u => u.id === 42); - Check presence:
javascript [1, 2, 3].includes(2); // true [1, 2, 3].indexOf(2); // 1 - Check conditions:
javascript users.some(u => u.active); // at least one active users.every(u => u.active); // all active
Tips
findreturnsundefinedif nothing matches; guard against it.includesuses SameValueZero equality, so it findsNaNcorrectly.
Common issues
- Using
indexOfwith objects returns-1because it compares by reference, not content. findandfindIndexstop at the first match; for all matches, usefilter.