loading...

forEach - filter 0-1

skiilaa profile image skiilaa ・1 min read

Let's say we have an array of pet foods:

var petFoods = [
    {
        name: "Cat Food",
        usableOn: ["cat"]
    },
    {
        name: "Dog Food",
        usableOn: ["dog"]
    },
    {
        name: "Pet Food",
        usableOn: ["cat", "dog"]
    }
];

...and let's say we want to get the foods that a cat can eat.

We would use a forEach loop, right?

var usableOnCats = [];

petFoods.forEach(function(food) {
    if (food.usableOn.includes("cat")) {
        usableOnCats.push(food);
    }
});

Alright, that's a bit long...

What if JS had something for arrays that specifically works for this purpose...

...oh wait, it totally does!

Let's use a filter loop:

var usableOnCats = petFoods.filter(function(food) {
    return food.usableOn.includes("cat");
});

...there you go. Much better, isn't it?

Posted on by:

Discussion

markdown guide
 

We would use a forEach loop, right?

Uh, no? 😅

Given that I do have seen junior developers doing this kind of mistake, it boggles my mind that they actually didn't knew about filter. And it's not like it's been introduced later than forEach!

Anyway, I think the title is supposing there's some kind of clash between these two methods. There isn't, they've been conceived for different goals.

 

The thing is, I’ve never seen filter in JS until I’ve got on this website. I always used to do this kind-of stuff w/ forEach. It’s crazy why they don’t promote this for junior devs.

 

Yeah, they should.

If you're a junior developer, you should either have a senior that tells you about these methods, or you have to find them yourself... Which is, of course, suboptimal 😕 Because as those methods are less commonly used, they could be overlooked.

Every time I have to introduce forEach to some junior, I always start with: "Let's talk about array methods..."