How to use Array.filter() in reactjs
Learning to code is sometimes frustrating, especially when you are a beginner and are stuck at a problem you can’t find a solution to.
One of the problems most beginners face at the start of their coding journey is understanding and using various different kinds of functions and methods, one of them is the array.filter() method. Whether you are filtering from an API in JSON format or from a local hard-coded array. Knowing array.filter() method can be really handy at times and if you are thinking of getting deep into the world of coding, chances are that you’ll end up using it a lot.
So, I’ll try to explain the array.filter() method in the most simple terms and how you can use it.
First, let’s have a look at the array we will be working on and the value each object of the array has.
The array contains around 10 objects, each object has 2 values i.e. name and age.
Now before we use the filter() method, we are going to map over the ‘data’ array. The code for the same looks like:
Output:
Now that we are done mapping over the ‘data’ array, let’s have a look at how useful at times the filter() method can be when you are working on a real-life project.
Let’s take an example of a situation where your boss asks you to only map over those objects whose age is less than or equal to 25.
So for that, right where you typed in the map() method, you’ll type in the filter() method and give it a function.
Take a look at how the filter() method looks like.
Essentially what we are doing here is, that we are defining the function of the filter() method to only return those objects whose age is less than or equal to 25. And once that condition has been met and the filtered array is returned, we let the map() method do its thing.
Let’s have a look how our new output looks like:
As you can see only those values are mapped over who have qualified our filter condition.
And that’s it, guys. If you understood the filter() method, you have no idea how much of your future self will be thankful to you for learning this.
All the best everyone! Hope you make superb projects and live your dream lifestyle.