0

Given the following array:

const array = [
{
    date: '2016-12-13T00:00:00.000Z',
    stats: [
      {
        name: 'Soft Drinks',
        sold: 34,
      },
      {
        name: 'Snacks',
        sold: 3,
      },
      {
        name: 'Coffee and warm drinks',
        sold: 26,
      },
    ],
  },
  {
    date: '2016-12-14T00:00:00.000Z',
    stats: [
      {
        name: 'Soft Drinks',
        sold: 34,
      },
      {
        name: 'Snacks',
        sold: 3,
      },
      {
        name: 'Coffee and warm drinks',
        sold: 26,
      },
    ],
  },
];

I would like to sum the sold values within the stats array. the final array should look like:

const array = [
  stats: [
    {
      name: 'Soft Drinks',
      sold: 68,
    },
    {
      name: 'Snacks',
      sold: 6,
    },
    {
      name: 'Coffee and warm drinks',
      sold: 52,
    },
  ],
]

So basically like initiate over the array dates, sum up the stats of every day, If the name match then += the value.

I did so far:

const result = {};
array.forEach(

(item) => {
    const { stats } = item;
    stats.forEach((item) => {
      Object
        .keys(item)
        .forEach((value) => {
          result[value] = (result[value] || 0) + item[value];
      });
  });
});

console.log(result);

But I'm kinda lost at the second loop. What is the proper way to achieve the result?

Ilanus
  • 6,690
  • 5
  • 13
  • 37
  • 1
    Your example "final" `array` is invalid, which makes it virtually impossible to make out what you really want to do. Could you update that? – T.J. Crowder Dec 13 '16 at 14:51
  • @Daenu: Better yet, a runnable example here on-site instead of off on another site, using Stack Snippets (the `[<>]` toolbar button). – T.J. Crowder Dec 13 '16 at 14:51
  • @T.J.Crowder True! Forgot that – toesslab Dec 13 '16 at 14:52
  • The error is in the `Object.keys` loop: you need to code the logic that says that the key is the `item.name`, and the sum is the `item.sold`. So: `stats.forEach((item) => { result[item.name] = (result[item.name] || 0) + item.sold });` Your current code combines all the keys, including the name. – user3297291 Dec 13 '16 at 14:56

0 Answers0