Find Index
JS Functions
Easy
10 min
arrays
lodash
indices
Implement findIndex(array, predicate, fromIndex) without using the built-in findIndex. It returns the index of the first element, searching forwards from fromIndex, for which predicate returns a truthy value. If no element matches, return -1.
const users = [
{ name: 'ada', active: false },
{ name: 'bob', active: true },
{ name: 'cy', active: true },
];
findIndex(users, (u) => u.active); // 1
findIndex(users, (u) => u.active, 2); // 2
findIndex(users, (u) => u.name === 'zed'); // -1
findIndex([1, 2, 3, 4], (n) => n % 2 === 0, -2); // 3 (starts at index 2)
Requirements
predicateis called aspredicate(value, index, array).fromIndexdefaults to0.- A negative
fromIndexcounts from the end (-1is the last element). If that still lands before0, start at0. - A
fromIndexat or past the end means there's nothing to search, so return-1. - Stop at the first match. Don't call the predicate for later elements.
Follow-up
- How would
findIndexdiffer fromindexOfforNaN? - Why might you prefer a
Mapfrom id to index if you callfindIndexmany times on the same list?
Spotted a mistake or a rights concern? Report an issue