2.7: filter
If you don't know the .filter()
method already, you need to know it. If you already know what it does, it doesn't hurt to practice it.
Let's add our data to the file, just an array of instructor objects, that includes their name and special skills:
Let's say that we want to iterate over this array and filter it based on the number of medals each instructor had. We only want to get instructors that have 5 or more medals.
What do we have to do here: 1. Manage the index. 2. Check the length. 3. Increment. 4. Create an empty array. 5. Etc.
We have to create an empty array to push the names into as we iterate through. This approach is fine for learning programming, but with ES6, the .filter function came along to make things more sleek for common tasks like iterating through a collection, and filtered based on a specific property.
Here it is:
Notice a few things here: 1. We create a variable called instructorNames that store the result as an array of objects. Note: filter()
returns a new array, and does NOT modify the original array. This is a huge thing, because you can safely use filter without having to worry about your original, and you can capture the value like we did above easily. 2. We are calling .filter on the instructors array: instructors.map
. 3. The instructor
parameter in .filter can be named anything, usually something related to the array. See how this is the exact same thing:
The
.filter()
function requires a return value. This is a key rule of using.filter()
, so the fat arrow is taking care of that requirement.Get some practice. Try the following. Fix the code:
.filter() and React
Filter is really commonly used in react. Especially when you're doing some sort of search, or filtering a big array of data. Filter is a great way to do this, so that you don't modify your original array, and can create a new array of only the information you want. With .filter()
and .map()
combined, there is a lot you can do without ever having to use a for loop.!
More tools
There are more things to know about React, and we will learn more of these tools. These are just some of the ones to get you started. Let's start seeing how these apply to what you'll be doing.
Last updated