Array findIndex() Method - Javascript Array

Javascript examples for Array:findIndex

Description

The findIndex() method returns the index of the first element that pass a test against a function.

If it finds an array element, findIndex() returns the index of that array element and does not check the remaining values

Otherwise it returns -1

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

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.
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.

Return Value:

Returns the array element index for passing the test, otherwise it returns -1

The following code shows how to Get the index of the first element in the array that has a value of 18 or more:

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<body>


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

<p>Index: <span id="demo"></span></p>

<script>
var ages = [4, 12, 16, 20];//from   w ww  . ja va  2s .c  o m

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

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

</body>
</html>

Related Tutorials