forEach - filter 0-1
Gerg艖 M贸ricz
Posted on November 18, 2017
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?
馃挅 馃挭 馃檯 馃毄
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.