JavaScript findIndex()Method
Example
Get the index position of the first element in the array with an age greater than or equal to 18
var ages = [3, 10, 18, 20];
function checkAdult(age) {
return age >= 18;
}
function myFunction() {
document.getElementById("demo").innerHTML = ages.findIndex(checkAdult);
}
fruitsOutput result:
2
Try it Yourself »
Definition and Usage
The findIndex() method returns the position of the first element in an array that passes a test condition (function).
The findIndex() method executes a function once for each element in the array:
- When an element in the array returns true under the test conditiontruethen findIndex() returns the index position of the matching element, and subsequent values will no longer call the execution function.
- If there is no matching element, it returns -1.
Note:For an empty array, findIndex() will not execute the function.
Note:findIndex() does not change the original array.
Browser Support
The numbers in the table specify the first browser version that supports the method.
| Method | |||||
|---|---|---|---|---|---|
| findIndex() | 45.0 | 12.0 | 25.0 | 7.1 | 32.0 |
Note:IE 11 and earlier versions do not support the findIndex() method.
Syntax
array.findIndex(function(currentValue, index, arr), thisValue)
Parameters
| Parameter | Description | ||||||||
|---|---|---|---|---|---|---|---|---|---|
| function(currentValue, index,arr) | Required. The function to be executed for each element of the array. Function parameters:
|
||||||||
| thisValue | Optional. A value to be passed to the function, generally used as the "this" value. If this parameter is empty, "undefined" will be passed to the "this" value. |
Technical Details
| Return value: | Returns the index of the first array element that passes the test; if there is no matching element, returns -1. |
|---|---|
| JavaScript Version: | ECMAScript 6 |
More Examples
Example
Returns the array index of the element that is greater than the number in the input box:
var ages = [4, 12, 16, 20];
function checkAdult(age) {
return age >= document.getElementById("ageToCheck").value;
}
function myFunction() {
document.getElementById("demo").innerHTML = ages.findIndex(checkAdult);
}
Try it Yourself »
Other Extensions
JavaScript Array Object