0

Given an array of objects like this:

[
  {
    playerId: 1,
    playerName: "Cooper",
    assists: 1,
    points: 5,
  },
  {
    playerId: 1,
    playerName: "Cooper",
    assists: 3,
    points: 2,
  },
  {
    playerId: 2,
    playerName: "Tom",
    assists: 1,
    points: 3,
  },
  {
    playerId: 2,
    playerName: "Tom",
    assists: 3,
    points: 1,
  },
  {
    playerId: 3,
    playerName: "Shelby",
    assists: 2,
    points: 7,
  },
  {
    playerId: 3,
    playerName: "Shelby",
    assists: 1,
    points: 2,
  },
]

Is there a way using ES6 to find matching object keys (playerId in this example) in an array of of objects, and then combine other object keys (assists and points) for those matches so the final array looks something like this:


[
  {
    playerId: 1,
    playerName: "Cooper",
    assists: 4,
    points: 7,
  },
  {
    playerId: 2,
    playerName: "Tom",
    assists: 4,
    points: 4,
  },
  {
    playerId: 3,
    playerName: "Shelby",
    assists: 3,
    points: 9,
  },
]
Clark Brent
  • 189
  • 1
  • 10

1 Answers1

1

You can use Array.prototype.reduce() to accumulate the properties, keeping track by reducing to an object that has the playerId as keys first, then using Object.values() to get back an array as intended.

let arrIn = [{"playerId":1,"playerName":"Cooper","assists":1,"points":5},{"playerId":1,"playerName":"Cooper","assists":3,"points":2},{"playerId":2,"playerName":"Tom","assists":1,"points":3},{"playerId":2,"playerName":"Tom","assists":3,"points":1},{"playerId":3,"playerName":"Shelby","assists":2,"points":7},{"playerId":3,"playerName":"Shelby","assists":1,"points":2}];

let arrOut = Object.values(arrIn.reduce((acc, current) => {
  let base = acc[current.playerId];
  if (!base) {
    // if we have not processed an object with this playerId yet,
    // simply copy the current object
    acc[current.playerId] = current;
  } else {
    // otherwise, increase the properties
    base.assists += current.assists;
    base.points += current.points;
  }

  return acc;
}, {}));
console.log(arrOut);
Constantin Groß
  • 10,719
  • 4
  • 24
  • 50