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 *


7 − four =

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>