JavaScript Array findIndex()
- Previous Page find()
- Next Page findLast()
- Go Back to the Previous Level JavaScript Array Reference Manual
Definition and Usage
findIndex()
The method returns the index of the first element in the array that passes the test (as a function provided).
findIndex()
The method executes the function once for each element existing in the array:
- If the findIndex() function returns a true value for the array element found, then findIndex() returns the index of the array element (and does not check the remaining values)
- Otherwise return -1
Note:findIndex()
It will not execute the function for array elements without values.
Note:findIndex()
It will not change the original array.
Instance
Example 1
Get the index of the first element in the array that is equal to or greater than 18:
var ages = [3, 10, 18, 20]; function checkAdult(age) { return age >= 18; } function myFunction() { document.getElementById("demo").innerHTML = ages.findIndex(checkAdult); }
Example 2
Get the index of the first element in the array that is greater than 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>
Syntax
array.findIndex(function(currentValue, index, arr), thisValue)
Parameter value
Parameters | Description | ||||||||
---|---|---|---|---|---|---|---|---|---|
function(currentValue, index, arr) | Required. The function to be run for each element in the array.
Function parameters:
|
||||||||
thisValue |
Optional. The 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: | If any element in the array passes the test, it returns the index of the array element, otherwise it returns -1. |
---|---|
JavaScript version: | ECMAScript 6 |
Browser support
The numbers in the table indicate the first browser version that fully supports this method.
Chrome | Edge | Firefox | Safari | Opera |
---|---|---|---|---|
Chrome 45 | Edge 12 | Firefox 25 | Safari 7.1 | Opera 32 |
September 2015 | July 2015 | July 2014 | September 2014 | September 2015 |
Note:Internet Explorer does not support findIndex()
Methods.
Related Pages
Tutorial:JavaScript Array
Tutorial:JavaScript Array Const
Tutorial:JavaScript Array Methods
Tutorial:JavaScript Array Sorting
Tutorial:JavaScript Array Iteration
- Previous Page find()
- Next Page findLast()
- Go Back to the Previous Level JavaScript Array Reference Manual