The JavaScript array findIndex() method returns the index of first element of the given array that satisfies the provided function condition. It returns -1, if no element satisfies the condition.
The JavaScript Array findIndex() method returns the index of the first array element that satisfies the provided test function or else returns -1.
The findIndex() method executes the function once for each element present in the array:
array.findIndex(function(currentValue, index, arr), thisValue)
Parameters: This method accepts five parameters as mentioned above and described below:
Return value:It returns the array element index if any of the elements in the array pass the test, otherwise it returns -1.
<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>