0

I'm trying to convert an array of numeric strings to integers, and am seeing something odd.

const ints = ['1','2','3'].map(parseInt);
console.log(ints);

The above code returns: [1, NaN, NaN]?

The 1 gets parsed correctly, but why are the 2 and 3 getting converted to NaN?

demo
  • 6,038
  • 19
  • 75
  • 149
grizzthedj
  • 7,131
  • 16
  • 42
  • 62

2 Answers2

0

callback is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed.

In your case you are actually calling

parseInt(1,0)
parseInt(2,1)
parseInt(3,2)

where first argument is the arrayElement and second is the radix or base

1 is valid Base 10 which is represented by radix 0 So 2 is not valid in base 1 and 3 is not valid in base 2

So the solution is to use arrow function

const ints = ['1','2','3'].map(num => parseInt(num));
console.log(ints);
kooskoos
  • 4,622
  • 1
  • 12
  • 29
0

So, I've discovered the answer.

When you pass just a function to .map, it passes ALL the arguments on to the function:

var customParseInt = function() {
    console.log('arguments', arguments);
}

var arr = ['1','2','3'];
arr.map(customParseInt);

Now, the first time it's called in your .map, the first argument is '1' and the second argument is the current index of the array, which is 0.

So for the first array element, you're calling parseInt('1', 0);

And for the second array element, you're calling parseInt('2', 1); -- again, first argument is the element, second argument is the index of the array.

If you look up the documentation, the second argument for parseInt is the radix. A radix of 0 does not error (probably because it defaults to a sensible value), but a radix of 1 or 2 makes the parseInt function behave fundamentally differently.

TKoL
  • 13,158
  • 3
  • 39
  • 73
  • But it [says](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt#Return_value): "If the radix is smaller than 2 or bigger than 36, and the first non-whitespace character cannot be converted to a number, NaN is returned." ? – ford04 Jan 08 '20 at 14:40
  • It does indeed say that, and I'm not sure if that's entirely true or slightly misleading personally, but you can test each value yourself in the console. – TKoL Jan 08 '20 at 14:44