Trusted answers to developer questions

What is the JavaScript Array filter()?

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

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() method
returned_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 which filter function is called.

Output

Returned: An array containing elements of the original array that satisfied all the conditions of the input function.

svg viewer

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 2020. 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 2020. 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)

RELATED TAGS

javascript
array
filter
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?