Q:

How to merge objects and sum just some values of duplicate objects?

Let's say I have an array of objects:

[
    1: {name: "john", id: 200, points: "333"},
    2: {name: "alice", id: 302, points: "20"},
    3: {name: "alice", id: 302, points: "13"},
    4: {name: "kevin", id: 501, points: "3"},
    5: {name: "adam", id: 999, points: "100"},
    6: {name: "adam", id: 999, points: "30"},
    7: {name: "adam", id: 999, points: "60"},
]

As you can see, they're already sorted (using lodash).
What I want to achieve is I want to merge objects with the same id and add the points. So it looks like this:

[
    1: {name: "john", id: 200, points: "333"},
    2: {name: "alice", id: 302, points: "30"},
    3: {name: "kevin", id: 501, points: "3"},
    4: {name: "adam", id: 999, points: "190"},
]

I'm using React and Lodash. There are about 7000 records in that array.

A:

Solution Without Lodash
var a = [
    {name: "john", id: 200, points: "333"},
    {name: "alice", id: 302, points: "20"},
    {name: "alice", id: 302, points: "13"},
    {name: "kevin", id: 501, points: "3"},
    {name: "adam", id: 999, points: "100"},
    {name: "adam", id: 999, points: "30"},
    {name: "adam", id: 999, points: "60"},
];

var o = {};

a.forEach((i) => {
  var id = i.id;
  i.points = parseInt(i.points)
  if (!o[id]) {
    return o[id] = i
  }
  return o[id].points = o[id].points + i.points
})

console.log(o)
var a2 = []
Object.keys(o).forEach((key) => {
 a2.push(o[key])
})

console.log(a2)

https://jsbin.com/dififukiqa/edit?js,console

