DEV Community

Gergő Móricz
Gergő Móricz

Posted on

4 1

forEach - filter 0-1

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?

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (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

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

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs