-2

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.

Jacopo
  • 143
  • 1
  • 1
  • 10
  • 1
    The outer array should probably use `[]` not `{}` – evolutionxbox Jul 27 '21 at 10:24
  • 2
    The example doesn't make much sense. Ignoring the invalid syntax... Where do the numbers in the _"desired output"_ come from? And where did `'Apple'` and `'Android'` go? – Andreas Jul 27 '21 at 10:24
  • If you want to group based on a column: [Sum of same nested array data using jquery](https://stackoverflow.com/q/67345005) and [Iterate over multi-dimensional array and return aggregated sum based on first index](https://stackoverflow.com/q/50240545) and [Summing a 2D array by “group”](https://stackoverflow.com/q/34678309) – adiga Jul 27 '21 at 10:28
  • Thank you all for the time and suggestions! the below answer actually worked! – Jacopo Jul 27 '21 at 10:51

1 Answers1

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);
Nitheesh
  • 19,238
  • 3
  • 22
  • 49