95

I want to convert the following string '14 2' into an array of two integers. How can I do it ?

T J
  • 42,762
  • 13
  • 83
  • 138

12 Answers12

226

A quick one for modern browsers:

'14 2'.split(' ').map(Number);

// [14, 2]`
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
xer0x
  • 12,970
  • 5
  • 32
  • 29
  • 2
    +1 and just add polyfill for older browser support if required https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Polyfill – qdev Oct 09 '15 at 08:03
  • 1
    nice, but how is this actually working? You are passing in the Number object but im not sure how its converting it. I thought you needed to pass in a function to map through. – Jarg7 May 31 '16 at 22:51
  • 2
    yep, that's right. Number() is the function passed to map, and it converts the values. Check out Todd's answer for more details. – xer0x Jun 09 '16 at 05:56
90

You can .split() to get an array of strings, then loop through to convert them to numbers, like this:

var myArray = "14 2".split(" ");
for(var i=0; i<myArray.length; i++) { myArray[i] = +myArray[i]; } 
//use myArray, it's an array of numbers

The +myArray[i] is just a quick way to do the number conversion, if you're sure they're integers you can just do:

for(var i=0; i<myArray.length; i++) { myArray[i] = parseInt(myArray[i], 10); } 
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • 5
    shorter: `for(var i=myArray.length; i--;) myArray[i] = myArray[i]|0;` using the bitwise conversion and shorter looping – vsync Jun 08 '11 at 23:13
  • 1
    or with ES5: `myArray.forEach(function(x,y,z){ z[y]=x|0 })` – vsync Jun 08 '11 at 23:26
  • 3
    @vsync - sure...but when any compiler is going to shorten it down even more than that, why make maintaining it painful? :) Clarity is worth a few extra bytes, especially when it won't actually be much longer if at all once minified down. – Nick Craver Jun 09 '11 at 00:24
  • because for once, I don't minify my published code, so others can read my code and see whats happening, and second, bitwise operations are much faster than parseInt. – vsync Jun 09 '11 at 00:37
  • 6
    @vsync - make sure you test that claim across all browsers, I personally find the + to be more readable...and if you test, most of the latest browsers there's a negligible difference, either way - depending on the engine. Also, you can offer a `.min.js` and `.js` if you want to expose your code...remember that minification isn't for obscurity (or shouldn't be, since it's about useless for that), it's for reducing HTTP overhead - a faster page load for your users. – Nick Craver Jun 09 '11 at 00:48
37

SO...older thread, I know, but...

EDIT

@RoccoMusolino had a nice catch; here's an alternative:

TL;DR:

 const intArray = [...("5 6 7 69 foo 0".split(' ').filter(i => /\d/g.test(i)))]

WRONG: "5 6 note this foo".split(" ").map(Number).filter(Boolean); // [5, 6]

There is a subtle flaw in the more elegant solutions listed here, specifically @amillara and @Marcus' otherwise beautiful answers.

The problem occurs when an element of the string array isn't integer-like, perhaps in a case without validation on an input. For a contrived example...

The problem:


var effedIntArray = "5 6 7 69 foo".split(' ').map(Number); // [5, 6, 7, 69, NaN]

Since you obviously want a PURE int array, that's a problem. Honestly, I didn't catch this until I copy-pasted SO code into my script... :/


The (slightly-less-baller) fix:


var intArray = "5 6 7 69 foo".split(" ").map(Number).filter(Boolean); // [5, 6, 7, 69]

So, now even when you have crap int string, your output is a pure integer array. The others are really sexy in most cases, but I did want to offer my mostly rambly w'actually. It is still a one-liner though, to my credit...

Hope it saves someone time!

Todd
  • 5,314
  • 3
  • 28
  • 45
27
var result = "14 2".split(" ").map(function(x){return parseInt(x)});
amillara
  • 304
  • 2
  • 2
  • 5
    Not all browsers support this - it'll break in IE, this is a JavaScript 1.6+ feature. Also, I said on another answer, always pass a radix to `parseInt()`. – Nick Craver Nov 27 '10 at 11:53
  • 2
    I so look forward to when we can use `.map` and similar in JS in any browser without additional libraries. – JAL Nov 27 '10 at 17:29
  • IE lives because we support it. Stop the agony! – Xilmiki Jul 28 '21 at 14:41
5

An alternative to Tushar Gupta answer would be :

'14 2'.split(' ').map(x=>+x);

// [14, 2]`

In code golf you save 1 character. Here the "+" is "unary plus" operator, works like parseInt.

Yann Rolland
  • 93
  • 1
  • 6
3

The point against parseInt-approach:

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

ankhzet
  • 2,517
  • 1
  • 24
  • 31
3

First split the string on spaces:

var result = '14 2'.split(' ');

Then convert the result array of strings into integers:

for (var i in result) {
    result[i] = parseInt(result[i], 10);
}
Marcus Whybrow
  • 19,578
  • 9
  • 70
  • 90
2

If the numbers can be separated by more than one space, it is safest to split the string on one or more consecutive whitespace characters (which includes tabs and regular spaces). With a regular expression, this would be \s+.

You can then map each element using the Number function to convert it. Note that parseInt will not work (i.e. arr.map(parseInt)) because map passes three arguments to the mapping function: the element, the index, and the original array. parseInt accepts the base or radix as the second parameter, so it will end up taking the index as the base, often resulting in many NaNs in the result. However, Number ignores any arguments other than the first, so it works directly.

const str = '1\t\t2   3 4';
const result = str.split(/\s+/).map(Number); //[1,2,3,4]

To remove elements that are not numbers, Array#filter can be used in conjunction with isNaN.

const str = '1\t\t2   3 ab  4 c';
const result = str.split(/\s+/).map(Number).filter(x => !isNaN(x)); //[1,2,3,4]

You could also use an anonymous function for the mapping callback with the unary plus operator to convert each element to a number.

const str = '1\t\t2   3 4';
const result = str.split(/\s+/).map(x => +x); //[1,2,3,4]

With an anonymous function for the callback, you can decide what parameters to use, so parseInt can also work.

const str = '1\t\t2   3 4';
const result = str.split(/\s+/).map(x => parseInt(x)); //[1,2,3,4]
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
0

Just for fun I thought I'd throw a forEach(f()) solution in too.

var a=[];
"14 2".split(" ").forEach(function(e){a.push(parseInt(e,10))});

// a = [14,2]
ocodo
  • 29,401
  • 18
  • 105
  • 117
-1
let idsArray = ids.split(',').map((x) => parseInt(x));
  • 1
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – Badacadabra Jun 12 '17 at 22:22
-1

Better one line solution:

var answerInt = [];
var answerString = "1 2 3 4";
answerString.split(' ').forEach(function (item) {
   answerInt.push(parseInt(item))
});
Ravi Gaur
  • 41
  • 1
  • 1
  • 7
-4

us the split function:

var splitresult = "14 2".split(" ");
pyvi
  • 675
  • 1
  • 4
  • 15