How to convert all elements in an array to integer in JavaScript?
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.
ECMAScript5 provides a map
method for Array
s, 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()
You can do
var arrayOfNumbers = arrayOfStrings.map(Number);
- MDN Array.prototype.map
For older browsers which do not support Array.map, you can use Underscore
var arrayOfNumbers = _.map(arrayOfStrings, Number);
var arr = ["1", "2", "3"];
arr = arr.map(Number);
console.log(arr); // [1, 2, 3]
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);
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.