forEach - filter 0-1

mogery

Gerg艖 M贸ricz

Posted on November 18, 2017

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?

馃挅 馃挭 馃檯 馃毄
mogery
Gerg艖 M贸ricz

Posted on November 18, 2017

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

forEach - filter 0-1
javascript forEach - filter 0-1

November 18, 2017