Return sum objects of an array in one

Asked

Viewed 50 times

1

Next, I’m a designer and I’m slowly learning javascript. One of the things I have the most difficulties with is objects and arrays, so I’m focusing more on that now. I have an array with 4 objects as the following code.

var players = [{
  name: "Batman",
  id: "1",
  points: 10
},
{
  name: "Superman",
  id: "2",
  points: 10
},
{
  name: "Batman",
  id: "1",
  points: 10
},
{
  name: "Superman",
  id: "2",
  points: 5
}
];

What I need: return objects with the same ids and points summed, resulting in 2 objects.

What is the logic I use to solve this problem? How to join objects with the same id and add the points of each one? I was able to do it with only 1 object, but I was comparing it with the id. If I had a much larger array, it would be almost impossible to keep comparing one by one. I want to understand the logic applied in this context.

1 answer

0


You have many ways, suggestions:

Creates a new object with a for:

var players = [{
    name: "Batman",
    id: "1",
    points: 10
  },
  {
    name: "Superman",
    id: "2",
    points: 10
  },
  {
    name: "Batman",
    id: "1",
    points: 10
  },
  {
    name: "Superman",
    id: "2",
    points: 5
  }
];

var obj = {};
for (var i = 0; i < players.length; i++) {
  var id = players[i].id;
  if (!obj[id]) obj[id] = players[i]; // caso ainda não haja um objeto com essa ID
  else obj[id].points += players[i].points;
}

console.log(obj);

Uses the .reduce():

var players = [{
    name: "Batman",
    id: "1",
    points: 10
  },
  {
    name: "Superman",
    id: "2",
    points: 10
  },
  {
    name: "Batman",
    id: "1",
    points: 10
  },
  {
    name: "Superman",
    id: "2",
    points: 5
  }
];
var obj = players.reduce(function(obj, player) {
  if (!obj[player.id]) obj[player.id] = player; // caso ainda não haja um objeto com essa ID
  else obj[player.id].points += player.points;
  return obj;
}, {});

console.log(obj);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.