Javascript - Array findIndex() Method

The findIndex() method returns the index of the first element in an array that pass a test.

Description

The findIndex() method returns the index of the first element in an array that pass a test.

The findIndex() method executes the function once for each element present in the array:

  • If it finds an array element where the function returns a true value, findIndex() returns the index of that array element (and does not check the remaining values)
  • Otherwise it returns -1

findIndex() does not run the function for array elements without values.

findIndex() does not change the original array.

Syntax

array.findIndex(function(currentValue, index, arr), thisValue)

Parameter Values

Parameter Require Description
function(currentValue, index,arr) Required. A function to be run for each element in the array.
thisValue Optional. A value to be passed to the function to be used as its "this" value. If this parameter is empty, the value "undefined" will be passed as its "this" value

For function(currentValue, index,arr)

ArgumentRequire Description
currentValueRequired. The value of the current element
index Optional. The array index of the current element
arr Optional. The array object the current element belongs to

Return

Returns the array element index if any of the elements in the array pass the test, otherwise it returns -1

Example

Get the index of the first element in the array that has a value of 18 or more:

Demo

var ages = [3, 10, 18, 20];

function checkAdult(age) {
    return age >= 18;
}

console.log( ages.findIndex(checkAdult));

Result

Array findIndex() method returns the index position.

If none of the elements in the collection match the callback (element, index, array) criteria, the return value is -1.

The syntax for the find() method looks like this:

arr.findIndex(callback[, thisArg]) 
  • where callback is the testing function that is executed on each value and takes three arguments: element, index and array.
function callback(element, index, array) { 
// returns true or false based on some condition 
} 
const inventory = [ 
       {name: 'XMLs', quantity: 2}, 
       {name: 'Screens', quantity: 0}, 
       {name: 'Keyboards', quantity: 5} 
]; 
result = inventory.findIndex((fruit) => fruit.name === 'XMLs'); 
console.log(result);             // 0 
result = inventory.findIndex((fruit) => fruit.name === 'grapes'); 
console.log(result);             // -1