Array.findIndex

findIndex — Executes a provided function once per array element. If the function returns a true value, it will break the loop and return that index.

Description

Array.findIndex(function callback, [object this])

Parameters

Name Description Type Default Optional
callback See callback below. function No
this object Yes
callback

The following parameters is passed to the callback.

value

The value of the current index.

index

The current index.

array

The array.

Return values

integer. Returns the index of the found element or -1 if not found.

Changelog

Version Description
ES 6 Introduced.

Examples

Example #1 – findIndex example
var array = [2, 4, 8]; var result = array.findIndex(function () { console.log(this); return true; }); console.log(result); // 0
var arr = [2, 4, 8]; var result = arr.findIndex(function (value, index, array) { console.log(value, index, array); return true; }); console.log(result); // 0

Passing in a custom object for this.

var array = [2, 4, 8]; var result = array.findIndex(function () { console.log(this); return true; }, document.location); console.log(result); // 0

Emulates a failed test when the value 2 is discovered. This will make it go to the next iteration.

var array = [2, 4, 4, 8]; var result = array.findIndex(function (value) { if (value === 2) { return false; } return true; }); console.log(result); // 1

And if all tests fail.

var array = [2, 4, 8]; var result = array.findIndex(function (value) { console.log(value); return false; }); console.log(result); // -1

External references