Back to blog

Filter: The Art of Selecting Data in Functional Programming with JavaScript 🚀

If you've ventured into the world of JavaScript, you've probably already crossed paths with Functional Programming. If this term is still unknown to you, no problem! It's an approach that allows you to write cleaner code and helps to prevent errors and make the code easier to understand and maintain. One of the most practical methods in Functional Programming is the Filter, which makes it possible to select data from an array in an uncomplicated and efficient way.

But what is a Filter and how does it work? 🤔

Advertisement

In short, the Filter is a function that takes a callback function as an argument and returns a new array containing only the elements that satisfy the condition defined in the callback function. In other words, it goes through each item in the original array and applies the callback function, returning a new array with the items that passed the "filter".

Why is this useful? 🤔

Suppose you have an array of numbers and you need to select only the even numbers. Without Filter, you would need to write a loop to iterate through each item in the array, check if the number is even and, if it is, add it to the new array. With Filter, you can pass the checking logic as a callback function and get the filtered array in a single line of code!

Let's move on to a practical example:

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];const pairs = numbers.filter(number => number % 2 === 0);console.log(pairs); // [2, 4, 6, 8]

In this example, we use Filter to create a new array containing only the even numbers in the original array.

What if I need a more complex filter? 🤔

Filter is extremely versatile and allows you to use any logic you like in the callback function. For example, suppose you have an array of objects representing people and you only need to select people over the age of 18. With Filter, you can easily do this:

const people = [  { name: 'John', age: 16 },  { name: 'Maria', age: 20 },  { name: 'Peter', age: 22 },  { name: 'Ana', age: 15 },];const olderOf18 = people.filter(person => person.age > 18);console.log(olderOf18);// [// { name: 'Maria', age: 20 },// { name: 'Pedro', age: 22 }// ]

In this example, we use Filter to create a new array containing only the objects that represent people over the age of 18.

Conclusion

The Filter is one of the most practical functions in JavaScript Functional Programming. It allows you to select data from an array quickly and easily, without the need for complex loops or conditionals. It is extremely flexible and can be used to perform simple or complex filters on data. So, if you're not already using Filter in your projects, start now and make your life a lot easier! 🚀

Advertisement

Let's go 🦅

Previous post Next post

Comments (0)

This article has no comments yet 😢. Be the first! 🚀🦅

Add comments