[javascript] How to convert a string of numbers to an array of numbers?

I have below string -

var a = "1,2,3,4";

when I do -

var b = a.split(',');

I get b as ["1", "2", "3", "4"]

can I do something to get b as [1, 2, 3, 4] ?

This question is related to javascript arrays

The answer is


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.


One liner

Array.from(a.split(','), Number)

Array.from() for details go to MDN

var a = "1,2,3,4";
var b = Array.from(a.split(','),Number);

b is an array of numbers


+string will try to change the string to a number. Then use Array.map function to change every element.

"1,2,3,4".split(',').map(function(el){ return +el;});

There's no need to use lambdas and/or give radix parameter to parseInt, just use parseFloat or Number instead.

Reasons:

  1. It's working:

    var src = "1,2,5,4,3";
    var ids = src.split(',').map(parseFloat); // [1, 2, 5, 4, 3]
    
    var obj = {1: ..., 3: ..., 4: ..., 7: ...};
    var keys= Object.keys(obj); // ["1", "3", "4", "7"]
    var ids = keys.map(parseFloat); // [1, 3, 4, 7]
    
    var arr = ["1", 5, "7", 11];
    var ints= arr.map(parseFloat); // [1, 5, 7, 11]
    ints[1] === "5" // false
    ints[1] === 5   // true
    ints[2] === "7" // false
    ints[2] === 7   // true
    
  2. It's shorter.

  3. It's a tiny bit quickier and takes advantage of cache, when parseInt-approach - doesn't:

      // execution time measure function
      // keep it simple, yeah?
    > var f = (function (arr, c, n, m) {
          var i,t,m,s=n();
          for(i=0;i++<c;)t=arr.map(m);
          return n()-s
      }).bind(null, "2,4,6,8,0,9,7,5,3,1".split(','), 1000000, Date.now);
    
    > f(Number) // first launch, just warming-up cache
    > 3971 // nice =)
    
    > f(Number)
    > 3964 // still the same
    
    > f(function(e){return+e})
    > 5132 // yup, just little bit slower
    
    > f(function(e){return+e})
    > 5112 // second run... and ok.
    
    > f(parseFloat)
    > 3727 // little bit quicker than .map(Number)
    
    > f(parseFloat)
    > 3737 // all ok
    
    > f(function(e){return parseInt(e,10)})
    > 21852 // awww, how adorable...
    
    > f(function(e){return parseInt(e)})
    > 22928 // maybe, without '10'?.. nope.
    
    > f(function(e){return parseInt(e)})
    > 22769 // second run... and nothing changes.
    
    > f(Number)
    > 3873 // and again
    > f(parseFloat)
    > 3583 // and again
    > f(function(e){return+e})
    > 4967 // and again
    
    > f(function(e){return parseInt(e,10)})
    > 21649 // dammit 'parseInt'! >_<
    

Notice: In Firefox parseInt works about 4 times faster, but still slower than others. In total: +e < Number < parseFloat < parseInt


Matt Zeunert's version with use arraw function (ES6)

const nums = a.split(',').map(x => parseInt(x, 10));

Since all the answers allow NaN to be included, I thought I'd add that if you want to quickly cast an array of mixed values to numbers you can do.

var a = "1,2,3,4,foo,bar";

var b = a.split(',');

var result = b.map(_=>_|0) // Floors the number (32-bit signed integer) so this wont work if you need all 64 bits.

// or b.map(_=>_||0) if you know your array is just numbers but may include NaN.

Map it to integers:

a.split(',').map(function(i){
    return parseInt(i, 10);
})

map looks at every array item, passes it to the function provided and returns an array with the return values of that function. map isn't available in old browsers, but most libraries like jQuery or underscore include a cross-browser version.

Or, if you prefer loops:

var res = a.split(",");
for (var i=0; i<res.length; i++)
{
    res[i] = parseInt(res[i], 10);
}

You can use JSON.parse, adding brakets to format Array

_x000D_
_x000D_
const a = "1,2,3,4";
const myArray = JSON.parse(`[${a}]`)
console.log(myArray)
console.info('pos 2 = ',  myArray[2])
_x000D_
_x000D_
_x000D_


A more shorter solution: map and pass the arguments to Number:

_x000D_
_x000D_
var a = "1,2,3,4";_x000D_
var b = a.split(',');_x000D_
console.log(b);_x000D_
var c = b.map(Number);_x000D_
console.log(c);
_x000D_
_x000D_
_x000D_


This is very simple.Such as:

["1", "2", "3", "4"].map(i=>Number(i))

you can run the demo.

_x000D_
_x000D_
let result = ["1", "2", "3", "4"].map(i=>Number(i));
console.log(result);
_x000D_
_x000D_
_x000D_


The underscore js way -

var a = "1,2,3,4",
  b = a.split(',');

//remove falsy/empty values from array after split
b = _.compact(b);
//then Convert array of string values into Integer
b = _.map(b, Number);

console.log('Log String to Int conversion @b =', b);

As a variant you can use combiantion _.map and _.ary methods from the lodash library. Whole transformation will be a more compact. Here is example from the official documentation:

_.map(['6', '8', '10'], _.ary(parseInt, 1));
// ? [6, 8, 10]

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;
};

You can transform array of strings to array of numbers in one line:

const arrayOfNumbers = arrayOfStrings.map(e => +e);