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

4

1 Answer 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);

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.