JavaScript Array Filter

Dan Nolan
ChainShot
Published in
2 min readOct 17, 2019

With JavaScript’s Array.prototype.filter we can start with an array of elements and take the ones that satisfy a condition. For a visual, let’s look at some squares. We’ll only take the blue squares:

Take only blue squares

We start with 7 squares and take only the squares who are blue, resulting in a new array of 4 squares.

For something more tangible we can express a condition using numbers. Say we had an array of numbers and we wanted to take only the values that are less than 5:

Take only values less than 5

We can express this in JavaScript code pretty easily!

const result = [4,3,5,2,7,8,1].filter(function(x) {
return x < 5;
});
console.log(result); // [4,3,2,1]

Filter lets us apply a function to each element and take only those values where the function returns true.

In the above example, we passed an anonymous function to filter. We can also use already declared functions:

function lessThanFive(x) {
return x < 5;
}
const result = [4,3,5,2,7,8,1].filter(lessThanFive);console.log(result); // [4,3,2,1]

Want to practice using filter?

Try out these code exercises!

Visit www.chainshot.com, follow this publication or find us on Twitter for more tutorials!

--

--