96

I am getting an array after some manipulation. I need to convert all array values as integers.

My sample code

var result_string = 'a,b,c,d|1,2,3,4';
result = result_string.split("|");
alpha = result[0];
count = result[1];
// console.log(alpha);
// console.log(count);
count_array = count.split(",");

count_array now contains 1,2,3,4 but I need these value to be in integers.

I had used parseInt(count_array);, but it fails. JS considers each value in this array as string.

jak.b
  • 273
  • 4
  • 15
Mohan Ram
  • 8,345
  • 25
  • 81
  • 130

14 Answers14

172

ECMAScript5 provides a map method for Arrays, applying a function to all elements of an array. Here is an example:

var a = ['1','2','3']
var result = a.map(function (x) { 
  return parseInt(x, 10); 
});

console.log(result);

See Array.prototype.map()

showdev
  • 28,454
  • 37
  • 55
  • 73
dheerosaur
  • 14,736
  • 6
  • 30
  • 31
120

You can do

var arrayOfNumbers = arrayOfStrings.map(Number);

For older browsers which do not support Array.map, you can use Underscore

var arrayOfNumbers = _.map(arrayOfStrings, Number);
Jonas Anseeuw
  • 3,590
  • 5
  • 22
  • 23
  • 2
    Very nice. If you use underscores (for old browsers which do not support Array.map), you can do `var newArray = _.map(oldArray, Number);` – Anh Tran Jun 25 '15 at 04:35
  • The underscore doesn't work for me, I'm using updated Chrome Version 80.0.3987.132, I'm getting `_ is not defined` – Olawale Oladiran Mar 17 '20 at 14:26
  • Very nice. How does this work? Usually map takes a function, like this: `val => Number(val)` – Dror Bar Oct 25 '20 at 09:44
45

Number() can convert a string to a number like this:

var arr = ["1", "2", "3"];
arr = arr.map(Number);
console.log(arr); // [1, 2, 3]
Welcor
  • 2,431
  • 21
  • 32
chzwzrd
  • 493
  • 4
  • 4
  • This is a correct answer, but it is substantially no different than another answer to this question that already has 47 upvotes. Furthermore, answers are much more helpful if they include an explanation of what the code is intended to do, and why that solves the problem without introducing others. – Tom Aranda Dec 19 '17 at 03:15
  • 2
    @TomAranda Oops, my bad...this was my first answer post, so I may have been a little too eager to put in my 2 cents. Should have read through all of the answers carefully before submitting my own. Thanks for the feedback! I will keep it in mind. – chzwzrd Dec 20 '17 at 17:56
  • 1
    Nice answer! Keep it up – CandleCoder Jul 19 '19 at 11:24
27

You need to loop through and parse/convert the elements in your array, like this:

var result_string = 'a,b,c,d|1,2,3,4',
    result = result_string.split("|"),
    alpha = result[0],
    count = result[1],
    count_array = count.split(",");
for(var i=0; i<count_array.length;i++) count_array[i] = +count_array[i];
//now count_array contains numbers

You can test it out here. If the +, is throwing, think of it as:

for(var i=0; i<count_array.length;i++) count_array[i] = parseInt(count_array[i], 10);
Ralf
  • 569
  • 4
  • 14
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • 3
    Actually, `parseInt("8foo", 10)` returns `8` while `+"8foo"` returns `NaN`. Your approach is actually more strict with invalid numbers, I like it. – Álvaro González Dec 14 '10 at 10:30
  • 1
    I might also suggest using something like `"74" >> 0`, a bitwise shift right by zero. Does the job well, is strict, and much more efficient than the alternatives. The second-best option efficiency-wise is doing a "not not" operation: `~~"74"` – Ruben Martinez Jr. Jul 08 '14 at 16:41
  • @RubenMartinezJr. It's not that strict because `"Not a number" >> 0 == 0` – Kian Jun 18 '15 at 12:02
7

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
7

Just loop the array and convert items:

for(var i=0, len=count_array.length; i<len; i++){
    count_array[i] = parseInt(count_array[i], 10);
}

Don't forget the second argument for parseInt.

Álvaro González
  • 142,137
  • 41
  • 261
  • 360
7

If you want to convert an Array of digits to a single number just use:

Number(arrayOfDigits.join(''));

Example

const arrayOfDigits = [1,2,3,4,5];

const singleNumber = Number(arrayOfDigits.join(''));

console.log(singleNumber); //12345
Juanma Menendez
  • 17,253
  • 7
  • 59
  • 56
5
var inp=readLine();//reading the input as one line string
var nums=inp.split(" ").map(Number);//making an array of numbers
console.log(nums);`

input : 1 9 0 65 5 7 output:[ 1, 9, 0, 65, 5, 7 ]

what if we dont use .map(Number)

code

var inp=readLine();//reading the input as one line string
var nums=inp.split(" ");//making an array of strings
console.log(nums);

input : 1 9 0 65 5 7 output:[ '1', '9', '0', '65', '5', '7']

Siva
  • 1,481
  • 1
  • 18
  • 29
Rithik Singh
  • 115
  • 2
  • 4
4
const arrString = ["1","2","3","4","5"];
const arrInteger = arrString.map(x => Number.parseInt(x, 10));

Above one should be simple enough,

One tricky part is when you try to use point free function for map as below

const arrString = ["1","2","3","4","5"];
const arrInteger = arrString.map(Number.parseInt);

In this case, result will be [1, NaN, NaN, NaN, NaN] since function argument signature for map and parseInt differs

map expects - (value, index, array) where as parseInt expects - (value, radix)

Mohan Ram
  • 8,345
  • 25
  • 81
  • 130
2

How about this:

let x = [1,2,3,4,5]
let num = +x.join("")
梅云飞
  • 31
  • 1
0

Using jQuery, you can like the map() method like so;

 $.map(arr, function(val,i) { 
     return parseInt(val); 
 });
Matt
  • 74,352
  • 26
  • 153
  • 180
nitzan
  • 319
  • 1
  • 14
0

use "join()"

let digits =[1,2,3,4]
let number =digits.join("")
console.log(number)

the '("")'- is used to indicate the separator,if you use 'digits.join("a")', it will give : 1a2a3a4

0

To convert array of Integer to a Integer value you can use reduce() method of Javascript. Below is the example :

    const arrayOfDigits = [1, 2, 3, 4, 5];
    const int = arrayOfDigits.reduce((val, digit) => (val * 10) + digit, 0);
    console.log('Array to Integer : '+int); //12345
    console.log('Add to Integer : '+(int+1)); //123456
0

The simplest way to do this is to convert the array into string and then parse it as integer:

var result_string = 'a,b,c,d|1,2,3,4';
result = result_string.split("|");
alpha = result[0];
count = result[1];
console.log(alpha);
console.log(count);
count_array = parseInt(count.split(",").join(''));
console.log(count_array);