Javascript Array Map With ParseInt Function

Javascript Array Map With ParseInt Function

When you want to turn all elements in an array from strings to integers, it comes to common sense that you want to use the Array.prototype.map function with Javascript’s built-in function parseInt:            
var numbers = ["1", "2", "3"];
var new_numbers = numbers.map(parseInt);
However, this will give you unexpected output of:
[ 1, NaN, NaN ]
Why? Well, this is because “map” passes more arguments into the callback function:
callback(item, index, array);
This works fine if your callback function only accepts one arguments, which will be “item”. However, “parseInt” function receives two arguments:
parseInt(string, base)
So in our case the actual value of “index” got interpreted as “base” in the parseInt function, and of course it will give you very unexpected result. The solution is to create a small function which wraps the “parseInt”:
var numbers = ["1", "2", "3"];
var new_numbers = numbers.map(function(x) { return parseInt(x, 10) })
This should get you green lights in your test cases :).

Leave a Reply

Your email address will not be published. Required fields are marked *

My new Snowflake Blog is now live. I will not be updating this blog anymore but will continue with new contents in the Snowflake world!