Filter() Method

listening to willow on October 2nd, 2021

Filter() is probably one of the methods I used the most on my latest project. There was a TON of filtering to do depending on the product page data response. I'm going to try to explain it in ezpz terminology. I'm wondering if I can use some IRL examples, but just replace the data with dummy data... it's a good idea for a part 2?


Anyways, filter(). I'm going to create an array of all my pets:

json
let pets = [
{
"name" : "argos",
"type" : "doggo",
"status" : "dead"
},
{
"name" : "oreo",
"type" : "doggo",
"status" : "alive"
},
{
"name" : "coco",
"type" : "doggo",
"status" : "alive"
},
{
"name" : "tweety",
"type" : "birb",
"status" : "dead"
},
{
"name" : "cloud",
"type" : "cat",
"status" : "alive"
},
{
"name" : "aeris",
"type" : "cat",
"status" : "alive"
},
{
"name" : "charlie",
"type" : "cat",
"status" : "alive"
}
]

Let's say I need to filter through this data and return my (unfortunately) dead pets. Pre-es6, it would look something like this:

js
let deadPets=[];
for(let x=0; x < pets.length; x++ ) {
if(pets[x].status === "dead") {
deadPets.push(pets[x]);
}
}
//result
[
{"name" : "argos","type" : "doggo","status" : "dead"},
{"name" : "tweety","type" : "birb","status" : "dead"}
]

With filter(), it looks so much cleaner.

js
pets.filter(function(pet){
return pet.status === 'dead';
});

view all posts