const menuItems = [
{ item: "Blue Cheese Salad", price: 8 },
{ item: "Spicy Chicken Rigatoni", price: 18 },
{ item: "Ponzu Glazed Salmon", price: 23 },
{ item: "Philly Cheese Steak", price: 13 },
{ item: "Baked Italian Chicken Sub", price: 12 },
{ item: "Pan Seared Ribeye", price: 31 }
];
const total = menuItems.reduce((accumulator, menuItem) => {
console.log(`
accumulator: ${accumulator},
menu item price: ${menuItem.price}
`);
return accumulator + menuItem.price;
}, 0);
console.log(total);
To get menu price total
const menuItems = [
{ item: "Blue Cheese Salad", price: 8 },
{ item: "Spicy Chicken Rigatoni", price: 18 },
{ item: "Ponzu Glazed Salmon", price: 23 },
{ item: "Philly Cheese Steak", price: 13 },
{ item: "Baked Italian Chicken Sub", price: 12 },
{ item: "Pan Seared Ribeye", price: 31 }
];
const mealChoices = menuItems.reduce((accumulator, menuItem) => {
return accumulator + menuItem.item + ', ';
}, '');
console.log(mealChoices);
To get all the meal item choices
Top comments (4)
FYI, if you include the text
javascript
immediately after starting the code markdown section, you can benefit from syntax highlighting.Also, in the second code example can be simplified.
@tracygjg My only issue with this is that it returns the first entry in the array as:
[object Object]
Is there a way to get around this? I tried adding an empty array as the first entry but i just return a comma before the rest of the entries.
Oops, sorry missed that. Yes there is a way by initialising the accumulator in the second argument of the reduce as an empty string; as you did originally. The only potential benefits of the approach I provided are:
Hope this helps, Tracy
Ahh! Thanks!