JavaScript Array findIndex()
Example 1
Find the first element with a value over 18:
ages.findIndex(checkAge);
function checkAge(age) {
return age > 18;
}
Description
The findIndex() method executes a function for each array element.
The findIndex() method returns the index (position) of the first element that passes a test.
The findIndex() method returns -1 if no match is found.
The findIndex() method does not execute the function for empty array elements.
The findIndex() method does not change the original array.
Array Find Methods:
| Method | Finds |
|---|---|
| includes() | Returns true if an array contains a specified value |
| indexOf() | The index of the first element with a specified value |
| lastIndexOf() | The index of the last element with a specified value |
| find() | The value of the first element that passes a test |
| findIndex() | The index of the first element that passes a test |
| findLast() | The value of the last element that passes a test |
| findLastIndex() | The index of the last element that passes a test |
Syntax
Parameters
A function to be run for each array element.
The value of the current element.
The index of the current element.
The array of the current element.
undefined.A value passed to the function as its
this value.
Return Value
Otherwise -1.
More Examples
Find the first element with a value above an input value:
<button onclick="myFunction()">Test</button>
<p>Any values above: <span id="demo"></span></p>
<script>
const numbers = [4, 12, 16, 20];
function checkValue(x) {
return x > document.getElementById("toCheck").value;
}
function myFunction() {
document.getElementById("demo").innerHTML = numbers.findIndex(checkValue);
}
</script>
Array Tutorials:
Browser Support
findIndex() is an ECMAScript6 (ES6 2015) feature.
JavaScript 2015 is supported in all browsers since June 2017:
| Chrome 51 |
Edge 15 |
Firefox 54 |
Safari 10 |
Opera 38 |
| May 2016 | Apr 2017 | Jun 2017 | Sep 2016 | Jun 2016 |