CARVIEW |
What is the JavaScript Array filter()?
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.
Syntax
Here is the function signature for the filter()
function in Javascript:
// function signature for the filter() methodreturned_values = values.filter(function)
As described above, the filter()
function takes two inputs.
Input
-
function:
A valid, pre-defined function. This can also be a lambda function. -
array:
The array on whichfilter
function is called.
Output
Returned: An array containing elements of the original array that satisfied all the conditions of the input function.
Examples
Let’s take a look at a couple of examples of how the filter()
method works:
1. Using pre-defined functions
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 20. 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)
2. Using a lambda function
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 20. 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)
Relevant Answers
Explore Courses
Free Resources