Javascript examples for Array:filter
The filter() method creates an array filled with all array elements that pass a test against another function.
filter() does not execute the function for array elements without values.
array.filter(function(currentValue, index, arr), thisValue)
Parameter | Description |
---|---|
function(currentValue, index,arr) | Required. A function to check for each element in the array. |
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 |
An Array containing all the array elements that pass the test. If no elements pass the test it returns an empty array.
The following code shows how to return an array of all the values in the ages array that are 18 or over:
<!DOCTYPE html> <html> <body> <p>Minimum age: <input type="number" id="ageToCheck" value="18"></p> <button onclick="myFunction()">Test</button> <span id="demo"></span> <script> var ages = [32, 33, 12, 40];/* www .j a v a2s. co m*/ function checkAdult(age) { return age >= document.getElementById("ageToCheck").value; } function myFunction() { document.getElementById("demo").innerHTML = ages.filter(checkAdult); } </script> </body> </html>