Filter an existing array to make a new one using filter()
Last updated: October 7, 2021.
The .filter()
method is a clean and powerful way to distill the elements of an array down to those we want to keep only. It is known as a higher-order or advanced array method because it accepts a custom function when called.
Here’s how to use it.
How filter() works
The method applies a custom function to each element in array.
Within the custom function, we write a test that returns true
or false
. If the outcome of the test is true
for an array element, it is added to a new array. If false
, it is not, i.e. it is filtered out.
So filter()
output a new array of only those elements that ‘pass’ the test we design.
Syntax
const newArray = myArray.filter(customFunction) function customFunction(arrayElement) { return // Test that returns true of false }
In the above code block, note that arrayElement
is available to customFunction
. This takes on the value of each element in the array that it is applied to.
We can even go full fancy pants and write it on one line using an arrow function 🔥🔥🔥
const newArray = myArray.filter(arrayElement => // Test )
Note that if the test is written within a normal function function, a return
statement is required, whereas if an arrow function is used, this can be omitted.
Usage examples
Filtering out scores of below 30:
const scores = [ 24, 54, 65, 34, 67, 4, 34, 78, 54, 24, 67, 43, 47] const goodScores = scores.filter(customFunction); function customFunction(score) { return score > 29 } console.log(goodScores) // [54,65,34,67,34,78,54,67,43,47]
Filtering out pesky unpaid members from the subscriber list:
const members = [ ["Brian","unpaid"], ["Dave","unpaid"],["Sue","paid"],["John","paid"],["Jessica","paid"],["Anton","unpaid"] ] const paidOnly = members.filter(member => member[1] == "paid"); console.log(paidOnly) // [ ["Sue","paid"],["John","paid"],["Jessica","paid"] ]