9

I have an array of strings like ['2', '10', '11'] and was wondering what's the most efficient way of converting it to an integer array. Should I just loop through all the elements and convert it to an integer or is there a function that does this?

MarksCode
  • 6,934
  • 15
  • 55
  • 114

4 Answers4

17

Use map() and parseInt()

var res = ['2', '10', '11'].map(function(v) {
  return parseInt(v, 10);
});

document.write('<pre>' + JSON.stringify(res, null, 3) + '<pre>')

More simplified ES6 arrow function

var res = ['2', '10', '11'].map(v => parseInt(v, 10));

document.write('<pre>' + JSON.stringify(res, null, 3) + '<pre>')

Or using Number

var res = ['2', '10', '11'].map(Number);

document.write('<pre>' + JSON.stringify(res, null, 3) + '<pre>')


Or adding + symbol will be much simpler idea which parse the string

var res = ['2', '10', '11'].map(v => +v );

document.write('<pre>' + JSON.stringify(res, null, 3) + '<pre>')


FYI : As @Reddy comment - map() will not work in older browsers either you need to implement it ( Fixing JavaScript Array functions in Internet Explorer (indexOf, forEach, etc.) ) or simply use for loop and update the array.

Also there is some other method which is present in it's documentation please look at Polyfill , thanks to @RayonDabre for pointing out.

Community
  • 1
  • 1
Pranav C Balan
  • 110,383
  • 23
  • 155
  • 178
  • Thanks for the suggestion! The only bad thing about this is it takes another array's worth of memory, but luckily my array isn't very big at all. – MarksCode Mar 03 '16 at 08:27
  • For compatibility issues, please note that Array.map() method is not available in IE8 and below – Rajshekar Reddy Mar 03 '16 at 08:28
  • 1
    [_Polyfill_](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Polyfill) is there.. – Rayon Mar 03 '16 at 08:46
2

You can use

var yourArray= yourArray.map(Number);

Using jQuery, you can use the map method as below

$.map(yourArray, function(value,index) { 
     return parseInt(value); 
 });
Rajshekar Reddy
  • 18,019
  • 3
  • 36
  • 56
2

You can simply use the Number object.

ḷet res = ['2', '10', '11'].map(Number);
sine99
  • 87
  • 1
  • 9
0

The simplest way to parse int from string is adding a + sign before:

var res = ['1', '2', '3'].map(function(v){return +v})
Max Peng
  • 2,501
  • 1
  • 24
  • 40