DEV Community

Cover image for Are you cool enough to get in? Understanding .filter
Rodman Lavalais
Rodman Lavalais

Posted on

Are you cool enough to get in? Understanding .filter

When it comes to .filter, imagine it as a body guard being the security of a party or some sort of get together. The security guards job is to only allow people on that list who meet the requirements. No matter how big or small, if a individual does not meet that requirement they won't be allowed into the function. Everyone who pass the test aka requirements are able to go inside and have a good time, while those who didn't have to watch from the outside. Funny way of thinking about it, but that's exactly how the higher order .filter functions.

Higher order functions are methods that make our life easier, when it comes to completing specific tasks or objectives when it comes to coding. Like if we wanted to loop through a specific data set, and apply a type of conditional, that code can be very long and become very repetitive. Higher order functions are a easier way to accomplish the same goal, while being able to write far less code.

When it comes to .filter, it's a higher order functions we apply to arrays, that when applied, it iterates over every element in the array for us, while returning a final array of elements that only passes the test. For example, if I wanted to look into an array and only return the elements that are less than the number 4, this is how that would look with a regular for loop and conditional

let arr = [1, 2, 3, 4, 5, 6, 7, 8];

let output = [];

for (let i = 0; i < arr.length; i++){
if (arr[i] < 4){
output.push(arr[i]);
}

}

console.log(output);

This here will return the array of output as [1, 2, 3];

However we could achieve this same result with .filter doing

function lessThan4(){
return arr.filter((ele) => {
return ele < 4;
})

}

console.log(lessThan4(arr));

Another cool this about .filter is that it not only iterates through an array for you, but it also returns creates a new array for you, so the original never gets mutated.

So the .filter higher order function acts as a body guard that only let's cool people in (specific elements in a array)...that passes a test. If they meet the requirements, they're allowed to go in and party, but if not they have to hate from outside of the club!

Top comments (0)