Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript map strange behaviour [duplicate]

Tags:

javascript

map

I was resolving some problems on codewars and tried to convert a string to a list of numbers like this:

"102904".split("").map(parseInt);

The expected result would be something like this:

[1, 0, 2, 9, 0, 4]

But it returns instead:

[1, NaN, NaN, NaN, 0, 4]

At believe that map should apply to each element in the list which are strings of 1 digits. One could believe that it isn't parsing correctly because the base isn't used but:

"102904".split("").map(function(x){ return parseInt(x);});
[ 1, 0, 2, 9, 0, 4]

Using parseInt(x, 10), doesn't change the result. But sending directly parseInt to map creates NaN...

I tried on Chrome and Firefox and I receive the same results.

like image 750
Loïc Faure-Lacroix Avatar asked Jan 12 '23 00:01

Loïc Faure-Lacroix


1 Answers

parseInt involves second argument - radix.

Your problem is that - map sends to arguments: item itself and index.

Problem digits are: 0, 2, 9

Why ?

  • 0 - has radix passed as 1. 1 isn't a legal radix so NaN
  • 2 - has radix passed as 2. In 2 base 2 is not available digit(0 and 1 are)
  • 9 - has radix passed as 3. Still 9 is not a valid digit(0, 1 and 2 are)
like image 183
lukas.pukenis Avatar answered Jan 24 '23 01:01

lukas.pukenis