0

I'm trying to pop numbers from the ranks array and add them all up in a counter variable. When I use +=, it doesn't add them up, it just sticks the numbers together and returns 10987. I'm using the let playerCountArray variable as a placeholder for the result. Any clues to what's wrong here?

const ranks = [2, 3, 4, 5, 6, 7, 8, 9, 10];
let playerCountArray = [];

playerCountArray += popArr(ranks)

let popArr = (arr) => {
    return arr.pop()
}

Thanks!

  • 2
    you have strings in your array, either store numbers instead or convert it to numbers. – Aalexander Feb 06 '21 at 09:04
  • Voting to close as _Not reproducible or was caused by a typo While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers._ – mplungjan Feb 06 '21 at 09:06
  • Remove the quotes or cast to number when reducing to sum them `const sum = ['2', '3', '4', '5', '6', '7', '8', '9', '10'].reduce((a,b)=> +a + +b)` – mplungjan Feb 06 '21 at 09:08
  • Thank you, yes I forgot to take out the quotes. I have tried to place the .reduce in the code but unsuccessful. This is what I was trying but throws an error: `playerCountArray += popArr(ranks).reduce((a,b)=> +a + +b)` – William9601 Feb 06 '21 at 09:28
  • The problem is that the counter is an array and not a number. Initialize it as 0 instead of [] and it will work. The problem, in general, is the automated casting of types in Javascript. It is a complex topic and I encourage you to look at that in-depth, you will find interesting things there. – Giorgos Papageorgiou Feb 06 '21 at 09:43
  • Oh amazing such a small thing has stalled me for hours! Thank you so much! Yes I'll look into that – William9601 Feb 06 '21 at 09:46

0 Answers0