Timothy W. Times
Timothy W. Times

Reputation: 31

Javascript - Adding Name/Scores (key/values) of an object within an array to get total scores in a new object with name/score as key/value

I've been stuck on this problem for hours, I can't seem to add the scores together and msot of the things I've tried end up giving me NaN or entirely wrong scores.

Example input is:

Example 1:
let ppl = [{name: "Anthony", score: 10},
            {name: "Fred", score : 10},
            {name: "Anthony", score: -8},
            {name: "Winnie", score: 12}];

My code which is not adding the scores together for multiple entries.

function countScores(people) {
  // Your code here

  let scoreCount = {};
  

  people.forEach(person => {  // Go through the people 

    let name = person.name; // Grab the name of the person
    let score = person.score // Grab the score of the person


    if (scoreCount[name]) {  //Check if name exists already and add scores together
      scoreCount[score] += person.score;
      console.log("Am I being accessed???")
    }

    score = Number(person.score);   // Grab the score of person and set it to score
    name = person.name;      // Grab the name of the person
    console.log(name, score);
    
    scoreCount[name] = score;


  })

    console.log(scoreCount)
    console.log("Endig Calculation of Scores....")
    return scoreCount;

};

My results are:

      + expected - actual

       {
      -  "Anthony": -8
      +  "Anthony": 2
         "Fred": 10
         "Winnie": 12
       }

Upvotes: 1

Views: 453

Answers (2)

flyingfox
flyingfox

Reputation: 13506

You can use reduce() to do it

let data = [{name: "Anthony", score: 10},
            {name: "Fred", score : 10},
            {name: "Anthony", score: -8},
            {name: "Winnie", score: 12}];
            
let result = data.reduce((a,v) =>{
  let exists = a[v.name]
  if(exists){
    a[v.name] += v.score
   }else{
    a[v.name] = v.score
   }
  return a
},{})
console.log(result)

Upvotes: 1

Amaarockz
Amaarockz

Reputation: 4684

Check the below implementation using reduce()

let ppl = [{name: "Anthony", score: 10},
            {name: "Fred", score : 10},
            {name: "Anthony", score: -8},
            {name: "Winnie", score: 12}];

function countScores(people) {
 let result = people.reduce((res, record) => {
  if(!res[record.name]) {
    res[record.name] = record.score;
  }else {
   res[record.name] += record.score;
  }
  return res;
 }, {});
 return result;
}


console.log(countScores(ppl));

Upvotes: 1

Related Questions