The Javascript arr.filter()
is used to apply a test to an array. It then returns all the values that pass this test in the form of an array.
It takes as an argument an array and a function and applies the function to each element in the array. Once done, it returns an array containing all the elements that pass the condition set by the argument function.
// function signature for the filter() methodreturned_values = values.filter(function)
As described above, the filter()
function takes two inputs.
array:
The array on which filter
function is called.Let’s take a look at a couple of examples of how the filter()
method works:
The values.filter() function is passed the function greaterThan20()
as input parameter.
This function checks which of the elements in the values
array is greater than or equal to . The function returns an array which is stored in the variable filtered
.
function greaterThan20(value) {return value >= 20;}var values = [34, 19, 24, 130, 14]var filtered = values.filter(greaterThan20);console.log(filtered)
The values.filter() function is passed a lambda function as input parameter.
This function checks which of the elements in the values
array is greater than or equal to . The function returns an array which is stored in the variable filtered
.
var values = [34, 19, 24, 130, 14]var filtered = values.filter(function(value) {return value >= 20;});console.log(filtered)
Free Resources