How to convert a string of numbers to an array of numbers?
You can use Array.map
to convert each element into a number.
var a = "1,2,3,4";
var b = a.split(',').map(function(item) {
return parseInt(item, 10);
});
Check the Docs
Or more elegantly as pointed out by User: thg435
var b = a.split(',').map(Number);
Where Number()
would do the rest:check here
Note: For older browsers that don't support map
, you can add an implementation yourself like:
Array.prototype.map = Array.prototype.map || function(_x) {
for(var o=[], i=0; i<this.length; i++) {
o[i] = _x(this[i]);
}
return o;
};
My 2 cents for golfers:
b="1,2,3,4".split`,`.map(x=>+x)
backquote is string litteral so we can omit the parenthesis (because of the nature of split function) but it is equivalent to split(',')
. The string is now an array, we just have to map each value with a function returning the integer of the string so x=>+x
(which is even shorter than the Number
function (5 chars instead of 6)) is equivalent to :
function(x){return parseInt(x,10)}// version from techfoobar
(x)=>{return parseInt(x)} // lambda are shorter and parseInt default is 10
(x)=>{return +x} // diff. with parseInt in SO but + is better in this case
x=>+x // no multiple args, just 1 function call
I hope it is a bit more clear.