The filter() method creates an array filled with all array elements that pass a test (provided as a function).
Note: filter() does not execute the function for array elements without values.
Syntax and Usage
array.filter(function(currentValue, index, arr), thisValue)
Parameter Values
function(currentValue, index,arr) -> Required. A function to be run for each element in the array.
Function arguments:
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.
If this parameter is empty, the value "undefined" will be passed as its "this" value
var numbers = [32, 33, 16, 10,40];
function check_number(number) { //if number is greater than 18 don't display
return number > = 18;
}
function number() {
document.getElementById("demo").innerHTML = numbers.filter(check_number);//get value from check_number
}
<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>
In above example return an array of all the values in the ages array that are a specific number or over
Complete Code For Array filter Method In JavaScript
<!DOCTYPE html>
<html>
<head>
<title>How To Use Array filter Method In JavaScript</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<style>
body{
color:white;
background: black;
}
</style>
<body>
<div class="container">
<br>
<br>
<div class="text-center">
<h1>Array Filter Method In JavaScript</h1>
</div>
<br>
<!-- <div class="well">-->
<button class="btn btn-primary" onclick="number()">Click it</button>
<h1 id="demo"></h1>
<!-- </div>-->
<br>
</div>
</body>
</html>
<script>
var numbers = [32, 33, 16, 10,40];
function check_number(number) {
return number >= 18;
}
function number() {
document.getElementById("demo").innerHTML = numbers.filter(check_number);
}
</script>