0
[{name:"A", value:10}, {name:"A", value:20}, {name:"B", value:15}, {name:"B", value:25}, {name:"C", value:30}]

I have an object like above , I want to sum the distinct name. output [A:30, B:40, C:30]. ES6 code preferable.

Dinesh Beura
  • 131
  • 1
  • 1
  • 7
  • 1
    What's the specific issue? What have you tried so far? – Dave Newton Apr 13 '21 at 16:57
  • Welcome to stackoverflow. Please take some time to read https://stackoverflow.com/help/how-to-ask. You should first research for your own, tell what you've tried to achieve the goal and add a [minimal reproducable example](https://stackoverflow.com/help/minimal-reproducible-example) to your question if possible. – biberman Apr 13 '21 at 16:57
  • I am unable to find a solution to this. tried with reduce and map functions – Dinesh Beura Apr 13 '21 at 16:58
  • Including your attempt(s) would be helpful. – Dave Newton Apr 13 '21 at 16:59

1 Answers1

1

You can use Array#reduce with an object to store the values for each name.

let arr = [{name:"A", value:10}, {name:"A", value:20}, {name:"B", value:15}, {name:"B", value:25}, {name:"C", value:30}];
let res = Object.values(arr.reduce((acc,curr)=>{
  (acc[curr.name] = acc[curr.name] || {name: curr.name, value: 0}).value += curr.value;
  return acc;
}, {}));
console.log(res);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80