English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

JavaScript array findIndex() method

 JavaScript Array Object

findIndex()The method returns the index of the first element in the array that satisfies the provided test function.

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

  • When the elements in the array return true when tested, findIndex() returns the index position of the element that meets the conditions, and the subsequent values will not call the execution function

  • If there is no element that meets the conditions, it will return -1

Note: The findIndex() method does not change the original array.

Note: The function will not be executed for an empty array for findIndex().

Syntax:

array.findIndex(callback, thisArg)
array.findIndex(function(element, index, arr), thisArg)
var num = [1, 30, 39, 29, 10, 13];
var val = num.findIndex(myFunc);
function myFunc(element) {
return element >= 18;
}
Test and See‹/›

See alsofind()A method that returns the value of the element found in the array instead of its index.

Browser compatibility

The numbers in the table specify the first browser version that fully supports the findIndex() method:

Method
findIndex()452532812

Parameter value

ParameterDescription
callback
A function that runs for each element in the array.
Function parameters:
  • element(Required)-The current element being processed in the array

  • index(Optional)-The index of the current element being processed in the array

  • arr(Optional)-Optional. The array object to which the current element belongs

thisArgOptional. The value passed to the function is generally the "this" value.
If this parameter is empty, "undefined" will be passed to the "this" value

Technical details

Return value:If the element passes the test, it is in the array.Index; otherwise it is-1
JavaScript Version:ECMAScript 6

More Examples

The following example returns the index of an element in the array that is a prime number; if there is no prime number, it returns-1:

var array1 = [1, 15, 17, 24, 29, 10, 13];
function isPrime(element) {
  var start = 2;
  while (start <= Math.sqrt(element)) {
     if (element % start < 1) {
         return false;
     } else {
         start++;
     }
  }
  return element > 1;
}
function myFunc1() {
   document.getElementById("result").innerHTML = array1.findIndex(isPrime);
}
Test and See‹/›

 JavaScript Array Object