-2

Take a look at below array

[{x: 'SomeName-1', value: 2}, 
 {x: 'SomeName-2', value: 3}, 
 {x: 'SomeName-1', value: 5},
 {x: 'SomeName-2', value: 8},
 {x: 'SomeName-1', value: 1},
 {x: 'SomeName-3', value: 4}]

how can i format this array so i will get x repeating single time with the addition of all its value. So the result will look like below

[{x: 'SomeName-1', value: 8}, {x: 'SomeName-2', value: 11}, {x: 'SomeName-3', value: 4},]

Thnaks in advance...

2
  • 1
    You could start by showing us what you have tried. Commented Apr 28, 2021 at 14:17
  • As you can see this question has been asked a few (hundred?) times Commented Apr 28, 2021 at 14:19

1 Answer 1

0

You can use reduce in order to group your values based on your .x property. Something as following:

const newList = list.reduce((items, item) => {
    const {x, value} = item;
  const itemIndex = items.findIndex(item => item.x === x)
  if(itemIndex === -1){
    items.push(item);
  } else {
    items[itemIndex].value += value;
  }
  
  return items;
}, []);

Or take a look at this fiddle

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

1 Comment

This mutates the objects in the original array.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.