Skip to content

Instantly share code, notes, and snippets.

@iaincollins
Created March 19, 2020 01:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iaincollins/17775b9596da868b1a44c2d425d229d8 to your computer and use it in GitHub Desktop.
Save iaincollins/17775b9596da868b1a44c2d425d229d8 to your computer and use it in GitHub Desktop.
Pizza Filter (long and short form example)
// 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)
// 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