0

Why does parseInt give NaN when I am not putting it in an arrow function? What's strange is that only 50 is getting properly parsed, while the others are not... Is there something wrong with putting parseInt itself as an argument? I want to make sure all of them are whole numbers, it works with an arrow function but I would like to know why it doesn't work just passing in the whole function. Even trying to bind it to window with .map(parseInt.bind(window)) doesn't work. Is it a problem with the source code?

function toPercent(array) {
    let arr = array.map((a, _, s) => a / s.reduce((a, b) => a+b) * 100)
    console.log(arr)
    return arr.map(parseInt)
}

console.log(toPercent([2, 1, 1]))

function toPercent(array) {
        let arr = array.map((a, _, s) => a / s.reduce((a, b) => a+b) * 100)
        console.log(arr)
        return arr.map(n => parseInt(n))
    }

    console.log(toPercent([2, 1, 1]))
MrMythical
  • 8,908
  • 2
  • 17
  • 45
  • 1
    What it looks like `return arr.map((n,index,array) => parseInt(n,index,array))` so you are setting the radix to be 1 and 2 for your number. – epascarello Mar 09 '22 at 17:06
  • Duplicate of https://stackoverflow.com/questions/262427/why-does-parseint-yield-nan-with-arraymap? – polo-language Mar 09 '22 at 17:07

1 Answers1

0

The callback to map is called with multiple parameters (element, index, array), and parseInt takes multiple parameters (string, radix) so the index is being passed as the radix. That's probably not what you intended.

The NaNs arise because the radix must be between 2 and 36. So you'll get some strange results radix is 1 and other indices will attempt to parse according to the ever-incrementing radix. By even further quirkiness, radix 0 means to use base 10 (unless the string starts with 0x or 0X, in which case it means to use base 16 ignoring the prefix in the expected way). parseInt returns NaN when parsing fails.

Wyck
  • 10,311
  • 6
  • 39
  • 60