JavaScript Arrays find


The JavaScript array find() method gets the first element of the array that has a specified value. Below is some modified sample code from w3schols.com.

<!DOCTYPE html>
<html>
<body>
<p>Click the button to check get the value of the <strong>first</strong> element in the array that has a value of 18 or more.</p>
<button onclick="myFunction()">Find it</button>
<p id="demo"></p>
<p><strong>Note:</strong> The find() method is not supported in IE 11 (and earlier versions).</p>
<script>
var ages = [3, 10, 18, 20];
function checkAdult(age) {
    return age >= 18;
}
function myFunction() {
    console.log(ages.find(checkAdult));
    document.getElementById("demo").innerHTML = ages.find(checkAdult);
}
</script>
</body>
</html>

The find() method returns the value of the first element in an array that pass a test (provided as a function). The find() method executes the function once for each element present in the array:

  • if it finds an array element where the function returns a true value, 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. Find() does not change the original array. Below is more modified code from w3schools.

<!DOCTYPE html>
<html>
<body>
<p>Click the button to return the value of the first element in the array that has a value equal to or above a specific number provided by the user.</p>
<p>Minimum age: <input type="number" id="ageToCheck" value="18"></p>
<button onclick="myFunction()">Try it</button>
<p>Value: <span id="demo"></span></p>
<p><strong>Note:</strong> The find() method is not supported in IE 11 (and earlier versions).</p>
<script>
var ages = [4, 12, 16, 20];
function checkAdult(age) {
    return age >= document.getElementById("ageToCheck").value;
}
function myFunction() {
    var agefromuser = document.getElementById("ageToCheck").value;
    var agefind = ages.find(checkAdult);
    // agefind will be a number or undefined
    if (agefind == undefined) {
    	agefind = "Sorry, unable to find any age equal to or above " + agefromuser;
    }
    document.getElementById("demo").innerHTML = agefind;
}
</script>
</body>
</html>

jsarrayfind1
jsarrayfind2

Leave a comment

Your email address will not be published. Required fields are marked *