Suppose i have an array of objects:
const arrayOfItems = [{id: 1, title: "Pizza"}, {id: 2, title: "Pizza"}, {id: 3, title: "Pasta"}]
How can i get the number of times Pizza is in the array? I am building a simple add to cart functionality in JS where i want to show how many pizza there is in the cart.
Advertisement
Answer
You can use Array.reduce
:
const arrayOfItems = [{id: 1, title: "Pizza"}, {id: 2, title: "Pizza"}, {id: 3, title: "Pasta"}] const pizzaOccurrences = arrayOfItems.reduce((a,b) => a += b.title == "Pizza" ? 1 : 0, 0) console.log(pizzaOccurrences)
Alternatively, you can use Array.filter
to remove the items whose title
property isn’t 'Pizza'
, then get the length:
const arrayOfItems = [{id: 1, title: "Pizza"}, {id: 2, title: "Pizza"}, {id: 3, title: "Pasta"}] const pizzaOccurrences = arrayOfItems.filter(e => e.title == "Pizza").length console.log(pizzaOccurrences)