The Problem
This is a very short post on how to be very careful when converting a collection (array) of strings to integersLet us assume that we receive from an API call or from some other source a collection of numbers in string format
Example
["1","9","2"]
In this case we might be planning to use the
mapfunction along with the
parseIntto get the job done as given below
["1","9","2"].map(parseInt)However, the catch here is that the above method will return the below response
(3) [1, NaN, NaN]
This will be a lot confusing to many because the first number gets parsed and the remaining ones does not.
Let us consider another example
Let us consider another example
["10","10","10","10"].map(parseInt)
This results in a similar output where the developer might get even puzzled
[10, NaN, 2, 3]
This looks like the last 2 numbers are getting printed like their indices
Okay, got you, how do I fix 'em now?
These issues are present, if we are not fully aware of the signature of the
parseIntmethod, which actually takes 2 arguments, the number and the base. The correct usage of
parseIntwill be
parseInt(10,10), where we provide the number and the base in which the number should be converted. Hence we get
10as the correct output. Okay, let us come back to our initial problem statement, how do we fix the code, well, we can convert to the below ones
["1","9","2"].map(x=>+x)
["10","10","10","10"].map(x=>+x)These will yeild the right result. Hence, please do take caution with the handling of the numbers and using map. Javascript is very flexible, but not knowing the details, it might result in unexpected outputs.
Comments
Post a Comment