Skip to content
Advertisement

Update object values

I’m having trouble updating the score property. I’m fairly new but still feel crazy not being able to figure this out.

‘fight’ is a string

function alphabetWar(fight) {
  let leftSide = {
    'w': 4,
    'p': 3,
    'b': 2,
    's': 1,
    'score': 0
  }

  let rightSide = {
    'm': 4,
    'q': 3,
    'd': 2,
    'z': 1,
    'score': 0
  }

  for (let char of fight) {
    if (leftSide.hasOwnProperty(char)) {
      leftSide.score += leftSide.char;
      if (rightSide.hasOwnProperty(char)) {
        rightSide.score += rightSide.char;
      }
    }
  }
  console.log(leftSide.score)
  if (leftSide.score === rightSide.score) return "Let's fight again!";
  return leftSide.score > rightSide.score ? 'Left side wins!' : 'Right side wins!';
}

Advertisement

Answer

You can try:

for (let char of fight.split('')) {
  if(typeof leftSide[char] != 'undefined'){
    leftSide.score += leftSide[char]
  }
  if(typeof rightSide[char] != 'undefined'){
    rightSide.score += rightSide[char]
  }
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement