jskatas.org Continuously Learn JavaScript. Your Way.

Array API: array.findIndex()

Array.prototype.findIndex() find the index of an item in an array.

Array.prototype.findIndex makes finding items in arrays easier

takes a compare function, returns the index where it returned true
const foundAt = [false, true].findIndex(item); assert.equal(foundAt, 1);
returns the first position it was found at
const foundAt = [0, 1, 1, 1].findIndex(item => item = 1); assert.equal(foundAt, 1);
returns -1 when nothing was found
const foundAt = [1, 2, 3].findIndex(item => item > 1); assert.equal(foundAt, -1);
the findIndex callback gets the item, index and array as arguments
const three = 3; const containsThree = arr => arr.indexOf(three) > -1; function theSecondThree(index, arr) { const preceedingItems = arr.slice(0, index); return containsThree(preceedingItems); } const foundAt = [1, 1, 2, 3, 3, 3].findIndex(theSecondThree); assert.equal(foundAt, 4);
combined with destructuring complex compares become short
const bob = {name: 'Bob'}; const alice = {name: 'Alice'}; const foundAt = [bob, alice].findIndex(({name:{length:l}}) => length > 3); assert.equal(foundAt, 1);

Required Knowledge

Related Katas

Array API

Difficulty Level

TBD

First Published

4 May 2015

Stats

5 tests to solve