-1

I have an Array of objects, for example:

 [{
      name: 'mike',
      id: 3312,
      points: 2,
      summary: 'example',
  }, {
      name: 'andrew',
      id: 4123,
      points: 1,
      summary: 'example',
  }, {
      name: 'mike',
      id: 0522,
      points: 5,
      summary: 'example',
  }]

I need to sum the points for each person, the problem I´m facing is there are more than 50 different person names so I can´t do something like this

for (let i = 0; i < issues.length; i++) {
    if (issues[i].name == 'mike') {
        //////////////////////
    }
}

Because the API in future can return a new Person.

5
  • 1
    There are different id values. Does this mean the primary key is going to be name? Commented Jun 19, 2018 at 10:45
  • What is the expected output? Commented Jun 19, 2018 at 10:46
  • 1
    @Praveen Kumar, yes, the ID i get it´s from an Issue ID, it´s different in every object! Commented Jun 19, 2018 at 10:46
  • Hi! You seem to have made a good start on it, but you've stopped in the middle. You need to actually sum up the values. Your best bet here is to do that (and any necessary research, search for related topics on SO, etc.). If you get stuck and can't get unstuck after doing more research and searching, post a minimal reproducible example of your attempt and say specifically where you're stuck. People will be glad to help. Good luck! Commented Jun 19, 2018 at 10:47
  • 1
    This has been asked and answered several times, so a really thorough search will turn up answers. Commented Jun 19, 2018 at 10:48

2 Answers 2

2

You can reduce into an object indexed by name:

const input = [{
   name: 'mike',
   id: 3312,
   points: 2,
   summary: 'example',
},
{
   name: 'andrew',
   id: 4123,
   points: 1, 
   summary: 'example',
},
{
   name: 'mike',
   id: 0522,
   points: 5,
   summary: 'example',
}];
const points = input.reduce((a, { name, points }) => (
  Object.assign(a, { [name]: (a[name] || 0) + points })
), {});
console.log(points);

Sign up to request clarification or add additional context in comments.

Comments

0

If you do not want to use reduce and keep things simple you can still use a forEach loop as below:

const input = [{
   name: 'mike',
   id: 3312,
   points: 2,
   summary: 'example',
},
{
   name: 'andrew',
   id: 4123,
   points: 1, 
   summary: 'example',
},
{
   name: 'mike',
   id: 0522,
   points: 5,
   summary: 'example',
}];

var res = {};

input.forEach((obj) => {
  res[obj.name] = res[obj.name] ? res[obj.name]+obj.points : obj.points;
});


console.log(res);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.