Home > database >  Modify an element in forEach doubles the entries
Modify an element in forEach doubles the entries

Time:05-22

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

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.

CodePudding user response:

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.

  • Related