2

I have this array

const data = [
  {"id": "One", "number": 100}, 
  {"id": "One", "number": 150}, 
  {"id": "One", "number": 200}, 
  {"id": "Two", "number": 50}, 
  {"id": "Two", "number": 100}, 
  {"id": "Three", "number": 10}, 
  {"id": "Three", "number": 90}
];

and I want to get the sum for each id and create a new array like this:

[
  {"id": "One", "number": 450},
  {"id": "Two", "number": 150}, 
  {"id": "Three", "number": 100}, 
]
1
  • 1
    Your data is in invalid format ,need to use "" instead of “” Commented Nov 6, 2022 at 8:31

2 Answers 2

3

You can implement it by using reduce() as follows:

const data = [
  {"id": "One", "number": 100}, 
  {"id": "One", "number": 150}, 
  {"id": "One", "number": 200}, 
  {"id": "Two", "number": 50}, 
  {"id": "Two", "number": 100}, 
  {"id": "Three", "number": 10}, 
  {"id": "Three", "number": 90}
];

const result = data.reduce((acc, {id, number}) => ({...acc, [id]: {id, number: acc[id] ? acc[id].number + number: number}}), {});

console.log(Object.values(result));

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

Comments

1

Don't know why you do not have a try,just using a simple reduce() can do it

const data = [{"id": "One", "number": 100}, 
  {"id": "One", "number": 150}, 
  {"id": "One", "number": 200}, 
  {"id": "Two", "number": 50}, 
  {"id": "Two", "number": 100}, 
  {"id": "Three", "number": 10}, 
  {"id": "Three", "number": 90}]

let result = data.reduce((a, v) => {
  let obj = a.find(i => i.id == v.id);
  if (obj) {
      obj.number += v.number;
  } else {
      a.push(v);
  }
  return a;
}, [])

console.log(result);

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.