Array find() Method - Javascript Array

Javascript examples for Array:find

Description

The find() method returns the first element that pass a test against a function.

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

Otherwise it returns undefined

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

Syntax

array.find(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.
currentValue Required. The value of the current element
index Optional. The array index of the current element
arrOptional. 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 value if any of the elements in the array pass the test, otherwise it returns undefined

The following code shows how to Get the value 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 ww  w  . ja va  2  s  . com*/

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

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

</body>
</html>

Related Tutorials