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

Modify an element in forEach doubles the entries

I’m currently setting up this js exercise here however it seems it’s not working corretcly as I got the duplication of all the entries, I cannot understand why.

Here’s the code:

export function updateScore(scoreBoard, player, points) {
  scoreBoard[player] = scoreBoard[player] + points;
  return scoreBoard;
}

export function applyMondayBonus(scoreBoard) {
  Object.keys(scoreBoard).forEach((element) =>{
  updateScore(scoreBoard,element,scoreBoard[element] + 100)
  } );
  return scoreBoard;
}

Once I run the code: I got this output

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

Object {
-   "Amil Pastorius": 445,
-   "Jesse Johnson": 222,
-   "Min-seo Shin": 119,
+   "Amil Pastorius": 790,
+   "Jesse Johnson": 344,
+   "Min-seo Shin": 138,
  }

Instead of this

{
      'Amil Pastorius': 445,
      'Min-seo Shin': 119,
      'Jesse Johnson': 222,
    };

Thanks in advance

EDIT: My bad, that was a logical error as @Ivar said, I’m passing scoreBoard[element] + 100 as a parameter, then again use scoreBoard[element] in scoreBoard[player] + points.

>Solution :

You could very simply write:

export function applyMondayBonus(scoreBoard = {}){
   Object.keys(scoreBoard).forEach(player => {
      scoreBoard[player] += 100
   })
   return scoreBoard
}

My advice would be to just write the function logic directly in the forEach loop. For such small and direct logic, a separate function could be a hassle.

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