I have an array of strings like ['2', '10', '11']
and was wondering what's the most efficient way of converting it to an integer array. Should I just loop through all the elements and convert it to an integer or is there a function that does this?
The string. split() method is used to split the string into various sub-strings. Then, those sub-strings are converted to an integer using the Integer. parseInt() method and store that value integer value to the Integer array.
Create an empty array with size as string length and initialize all of the elements of array to zero. Start traversing the string. Check if the character at the current index in the string is a comma(,). If yes then, increment the index of the array to point to the next element of array.
Use map()
and parseInt()
var res = ['2', '10', '11'].map(function(v) {
return parseInt(v, 10);
});
document.write('<pre>' + JSON.stringify(res, null, 3) + '<pre>')
More simplified ES6 arrow function
var res = ['2', '10', '11'].map(v => parseInt(v, 10));
document.write('<pre>' + JSON.stringify(res, null, 3) + '<pre>')
Or using Number
var res = ['2', '10', '11'].map(Number);
document.write('<pre>' + JSON.stringify(res, null, 3) + '<pre>')
+
symbol will be much simpler idea which parse the string
var res = ['2', '10', '11'].map(v => +v );
document.write('<pre>' + JSON.stringify(res, null, 3) + '<pre>')
map()
will not work in older browsers either you need to implement it ( Fixing JavaScript Array functions in Internet Explorer (indexOf, forEach, etc.) ) or simply use for loop and update the array.
Also there is some other method which is present in it's documentation please look at Polyfill , thanks to @RayonDabre for pointing out.
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