Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
       }

>Solution :

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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading