Using Array#map to convert arrays cleanly

Just a nice little Javascript tip that I came by awhile ago on Stackoverflow. If you have an array of strings and you want to convert it to an array of numbers the way you would commonly see that done is using parseInt:

var foo = ['1', '4', '2', '10', '3'];
var numbers = foo.map(function(num) {return parseInt(num, 10)});

That works, but it’s kind of wordy. There is actually a more concise option:

var numbers = foo.map(Number);

Instead of passing each item in the foo array to parseInt, we utilize the Number constructor. It also works in reverse, as you’re able to convert the number array back into a string array like so:

var strings = numbers.map(String);
This entry was posted in jQuery / Javascript, Web Development and tagged , , , . Bookmark the permalink.

Leave a Reply

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