Created
March 19, 2020 01:50
-
-
Save iaincollins/17775b9596da868b1a44c2d425d229d8 to your computer and use it in GitHub Desktop.
Pizza Filter (long and short form example)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Long form example | |
const pizzas = [ | |
{ | |
name: 'Margarita', | |
toppings: ['Cheese', 'Tomato'] | |
}, | |
{ | |
name: 'Hawaiian', | |
toppings: ['Cheese', 'Tomato', 'Ham', 'Pineapple'] | |
}, | |
{ | |
name: 'Ham and Mushroom', | |
toppings: ['Cheese', 'Tomato', 'Ham', 'Mushroom'] | |
}, | |
{ | |
name: 'Pepperoni', | |
toppings: ['Cheese', 'Tomato', 'Pepperoni'] | |
}, | |
{ | |
name: 'Vegetable', | |
toppings: ['Cheese', 'Tomato', 'Peppers', 'Mushroom'] | |
}, | |
] | |
const meats = ['Ham', 'Pepperoni'] | |
// Set 'vegetarian' to 'true' on pizzas that don't contain meats (and 'false' if they do) | |
pizzas.forEach(function(pizza) { | |
let pizzaHasMeat = false | |
meats.forEach(function(meat) { | |
pizza.toppings.forEach(function(topping) { | |
if (topping === meat) { | |
pizzaHasMeat = true | |
} | |
}) | |
}) | |
if (pizzaHasMeat) { | |
pizza.vegetarian = false | |
} else { | |
pizza.vegetarian = true | |
} | |
}) | |
// Filter by pizzas where vegetarian is true, and return just the names | |
const vegetarianPizzasByName = [] | |
pizzas.forEach(function(pizza) { | |
if (pizza.vegetarian) { | |
vegetarianPizzasByName.push(pizza.name) | |
} | |
}) | |
console.log('Vegetarian Pizzas:', vegetarianPizzasByName) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Short form example | |
const pizzas = [ | |
{ | |
name: 'Margarita', | |
toppings: ['Cheese', 'Tomato'] | |
}, | |
{ | |
name: 'Hawaiian', | |
toppings: ['Cheese', 'Tomato', 'Ham', 'Pineapple'] | |
}, | |
{ | |
name: 'Ham and Mushroom', | |
toppings: ['Cheese', 'Tomato', 'Ham', 'Mushroom'] | |
}, | |
{ | |
name: 'Pepperoni', | |
toppings: ['Cheese', 'Tomato', 'Pepperoni'] | |
}, | |
{ | |
name: 'Vegetable', | |
toppings: ['Cheese', 'Tomato', 'Peppers', 'Mushroom'] | |
}, | |
] | |
const meats = ['Ham', 'Pepperoni'] | |
// Set 'vegetarian' to 'true' on pizzas that don't contain meats (and 'false' if they do) | |
pizzas.map(pizza => pizza.vegetarian = !meats.some(meat => pizza.toppings.includes(meat)) ) | |
// Filter by pizzas where vegetarian is true, and return just the names | |
console.log('Vegetarian Pizzas:', pizzas.filter(pizza => pizza.vegetarian).map(pizza => pizza.name)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment