find() and findIndex()
find() & findIndex()
Section titled “find() & findIndex()”Introduction
Section titled “Introduction”find() returns the first element that passes a test. findIndex() returns the index of the first passing element.
Examples
Section titled “Examples”const numbers = [5, 12, 8, 130, 44];
numbers.find(x => x > 10); // 12numbers.findIndex(x => x > 10); // 1numbers.find(x => x > 200); // undefinedObjects
Section titled “Objects”const users = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 3, name: 'Charlie' }];
users.find(user => user.id === 2);// { id: 2, name: 'Bob' }Summary
Section titled “Summary”find— returns first matching element (or undefined)findIndex— returns index of first match (or -1)- Stops searching after first match (efficient)