Quick Concepts: Filter

Dean
1 min readSep 27, 2020

Filter is another higher-order function that’s available in many programing languages. While Map() applies a function to each item in an array and returns a new array filled with said elements, and Reduce() reduces an array down to one element, Filter() returns an array of elements that returns true when a function/comparison is ran against it.

For example, lets imagine we have an array of numbers,

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]

and we wanted to return an array filled only with numbers that are divisible by 3. We could use the filter() method to achieve that goal.

numbers.filter(num => num % 3 === 0)

What filter() is doing is going through each element and checking if the element (num) returns 0 when divided by 3. If it isn’t, the element is passed over, if it is, the element is pushed to an array that’s keeping track of all elements divisible by 3. At the end of the array of elements, you are returned the new array of elements divisible by 3.

[3, 6, 9]

--

--