THE WORLD'S LARGEST WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

JavaScript Array findIndex() Method

JavaScript Array Reference JavaScript Array Reference

Example

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

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

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

function myFunction() {
    document.getElementById("demo").innerHTML = ages.findIndex(checkAdult);
}

The result will be:

2
Try it Yourself »

More "Try it Yourself" examples below.


Definition and Usage

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

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 undefined

Note: findIndex() does not execute the function for array elements without values.

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


Browser Support

The numbers in the table specify the first browser version that fully supports the method.

Method
findIndex() 45.0 12.0 25.0 7.1 32.0

Syntax

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

Parameter Values

Parameter Description
function(currentValue, index,arr) Required. A function to be run for each element in the array.
Function arguments:
Argument Description
currentValue Required. 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
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

Technical Details

Return Value: Returns the array element index if any of the elements in the array pass the test, otherwise it returns undefined
JavaScript Version: ECMAScript 6

Examples

More Examples

Example

Get the index of the first element in the array that has a value above a specific number:

<p>Minimum age: <input type="number" id="ageToCheck" value="18"></p>
<button onclick="myFunction()">Try it</button>

<p>Any ages above: <span id="demo"></span></p>

<script>
var ages = [4, 12, 16, 20];

function checkAdult(age) {
    return age >= document.getElementById("ageToCheck").value;
}

function myFunction() {
    document.getElementById("demo").innerHTML = ages.findIndex(checkAdult);
}
</script>
Try it Yourself »

JavaScript Array Reference JavaScript Array Reference