'Calculate the sum of values within an array of objects [duplicate]

I am trying to find the total sum for each item sold inside an array, like so:

The array looks like this:

 [ 
  {
    'Some Title Item', '22', 'Apple'
  },
  {
    'Another Item', '12', 'Android'
  },
  {
    'Third Item', '15', 'Android'
  }, 
  {
    'Another Item', '6', 'Apple'
  },...
]

I already have a variable were I store all the titles/labels, and now need to find the sum of total items sold for each of those.



Solution 1:[1]

Your input and output must be arrays.

Use array.reduce for achieve your desired result.

const data = [
  [
    'Some Title Item', '22', 'Apple'
  ],
  [
    'Another Item', '12', 'Android'
  ],
  [
    'Third Item', '15', 'Android'
  ],
  [
    'Another Item', '6', 'Apple'
  ]
];
let output = [];
output = data.reduce((acc, curr) => {
  const node = acc.find((node) => node[0] === curr[0]);
  if (node) {
    node[1] += Number(curr[1]);
  } else {
    acc.push([curr[0], Number(curr[1])]);
  }
  return acc;
}, []);
console.log(output);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nitheesh