DEV Community

bomoniyi
bomoniyi

Posted on • Edited on

Tranforming arrays with .reduce()

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);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

To get all the meal item choices

Top comments (4)

Collapse
 
tracygjg profile image
Tracy Gilmore • Edited

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.

const mealChoices = menuItems.reduce((accumulator, menuItem) => 
  `${accumulator}, ${menuItem.item}`);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
bomoniyi profile image
bomoniyi • Edited

@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.

Collapse
 
tracygjg profile image
Tracy Gilmore

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:

  1. Use of a template literal to concatenate the strings.
  2. Use of the implicit return feature of arrow functions.

Hope this helps, Tracy

Collapse
 
bomoniyi profile image
bomoniyi

Ahh! Thanks!