Filtering an array on ES6
Jaime Rios
Posted on May 8, 2018
It’s been a while since ES6 was released, and now in 2017. Most of it’s features are widely supported on modern browsers.
Since most of you are already familiar (or not) with filtering arrays. Here is a refresher of how to filter arrays with arrow functions.
Disclaimer: I’m assuming a good level of familiarity with ES6. If you need it, here is an awesome post about arrow functions . This is a question I had a few months ago and I decided to make a post about the answer.
Given the following array of objects(aka collection)
let shoes = [{"brand":"Converse", "color": "blue" },
{"brand":"Nike", "color": "white" },
{"brand":"Adidas", "color": "red" },
{"brand":"Puma", "color": "black" }];
This array containing each pair of shoes you own, their brand and color. It is a rainy day, and you want a pair of shoes that can get the job done with out getting too dirty.
That’s why out of your collection of shoes, you only want to get the black ones.
In order to accomplish that, we are using filter(). This a method that creates a new array with all elements that pass the test implemented by the provided function.
How does this look like in code? Glad you ask. Here is the answer.
shoes.filter(shoe => shoe.color === "black");
What we have inside the filter() method, is a function where:
shoe
is the current element being processed in the array.
shoe.color === “black”
is the condition we want to evaluate.
Finally, here is all the code in one block for you to copy and paste in your console.
let shoes = [{"brand":"Converse", "color": "blue" },
{"brand":"Nike", "color": "white" },
{"brand":"Adidas", "color": "red" },
{"brand":"Puma", "color": "black" }];
shoes.filter(shoe => shoe.color === "black");
That’s all folks, thanks for reading.
Posted on May 8, 2018
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
June 25, 2023