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.
You can convert a String to integer using the parseInt() method of the Integer class. To convert a string array to an integer array, convert each element of it to integer and populate the integer array with them.
To convert an array of strings to an array of numbers, call the map() method on the array, and on each iteration, convert the string to a number. The map method will return a new array containing only numbers. Copied!
We can use the parseInt() method and valueOf() method to convert char array to int in Java. The parseInt() method takes a String object which is returned by the valueOf() method, and returns an integer value. This method belongs to the Integer class so that it can be used for conversion into an integer.
In JavaScript parseInt() function (or a method) is used to convert the passed in string parameter or value to an integer value itself. This function returns an integer of base which is specified in second argument of parseInt() function.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With