Return objects added from an array in one

1

Next, I'm a designer and I'm learning javascript slowly. One of the things that I have the most difficulties, are objects and arrays, so I'm focusing on it 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 added, resulting in 2 objects.

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

    
asked by anonymous 01.04.2017 / 20:29

1 answer

0

You have several 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 .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);
    
01.04.2017 / 20:37