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

Atal Shrivastava
  • 674
  • 1
  • 9
  • 35

1 Answers1

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

CapitanFindus
  • 1,498
  • 15
  • 26