DEV Community

loading...

forEach - filter 0-1

Gergő Móricz
programmer since 2013
・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"]
    }
];
Enter fullscreen mode Exit fullscreen mode

...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);
    }
});
Enter fullscreen mode Exit fullscreen mode

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");
});
Enter fullscreen mode Exit fullscreen mode

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

Discussion (3)

Collapse
maxart2501 profile image
Massimo Artizzu

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.

Collapse
mogery profile image
Gergő Móricz Author

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.

Collapse
maxart2501 profile image
Massimo Artizzu

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..."

Forem Open with the Forem app