I am getting an array after some manipulation. I need to convert all array values as integers.
My sample code
var result_string = \'
How about this:
let x = [1,2,3,4,5]
let num = +x.join("")
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);
var arr = ["1", "2", "3"];
arr = arr.map(Number);
console.log(arr); // [1, 2, 3]
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)
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);
Using jQuery, you can like the map() method like so;
$.map(arr, function(val,i) {
return parseInt(val);
});