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.
We can also convert String to String array by using the toArray() method of the List class. It takes a list of type String as the input and converts each entity into a string array.
To convert String to array in Python, use String. split() method. The String . split() method splits the String from the delimiter and returns the splitter elements as individual list items.
You can use Array.map
to convert each element into a number.
var a = "1,2,3,4";
var b = a.split(',').map(function(item) {
return parseInt(item, 10);
});
Check the Docs
Or more elegantly as pointed out by User: thg435
var b = a.split(',').map(Number);
Where Number()
would do the rest:check here
Note: For older browsers that don't support map
, you can add an implementation yourself like:
Array.prototype.map = Array.prototype.map || function(_x) {
for(var o=[], i=0; i<this.length; i++) {
o[i] = _x(this[i]);
}
return o;
};
My 2 cents for golfers:
b="1,2,3,4".split`,`.map(x=>+x)
backquote is string litteral so we can omit the parenthesis (because of the nature of split function) but it is equivalent to split(',')
. The string is now an array, we just have to map each value with a function returning the integer of the string so x=>+x
(which is even shorter than the Number
function (5 chars instead of 6)) is equivalent to :
function(x){return parseInt(x,10)}// version from techfoobar
(x)=>{return parseInt(x)} // lambda are shorter and parseInt default is 10
(x)=>{return +x} // diff. with parseInt in SO but + is better in this case
x=>+x // no multiple args, just 1 function call
I hope it is a bit more clear.
This is very simple.Such as:
["1", "2", "3", "4"].map(i=>Number(i))
you can run the demo.
let result = ["1", "2", "3", "4"].map(i=>Number(i));
console.log(result);
Map it to integers:
a.split(',').map(function(i){
return parseInt(i, 10);
})
map
looks at every array item, passes it to the function provided and returns an array with the return values of that function. map
isn't available in old browsers, but most libraries like jQuery or underscore include a cross-browser version.
Or, if you prefer loops:
var res = a.split(",");
for (var i=0; i<res.length; i++)
{
res[i] = parseInt(res[i], 10);
}
+string
will try to change the string to a number. Then use Array.map
function to change every element.
"1,2,3,4".split(',').map(function(el){ return +el;});
Array.from() for details go to MDN
var a = "1,2,3,4";
var b = Array.from(a.split(','),Number);
b
is an array of numbers
A more shorter solution: map and pass the arguments to Number
:
var a = "1,2,3,4";
var b = a.split(',');
console.log(b);
var c = b.map(Number);
console.log(c);
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