The filter() method creates an array filled with all array elements that pass a test (provided as a function).
The filter()
Array method creates a new array with elements that fall under a given criteria from an existing array:
The item argument is a reference to the current element in the array as filter() checks it against the condition. This is useful for accessing properties, in the case of objects.
array.filter(function(currentValue, index, arr), thisValue)
<p>Minimum age: <input type="number" id="ageToCheck" value="18"></p>
<button onclick="myFunction()">Try it</button>
<p>All ages above minimum: <span id="demo"></span></p>
<script>
var ages = [32, 33, 12, 40];
function checkAdult(age) {
return age >= document.getElementById("ageToCheck").value;
}
function myFunction() {
document.getElementById("demo").innerHTML = ages.filter(checkAdult);
}
</script>