Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string array to integer array

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?

like image 357
MarksCode Avatar asked Mar 03 '16 08:03

MarksCode


People also ask

How do I convert a string array to an Integer?

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.

Can we convert string to array in C?

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.


1 Answers

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>')


Or adding + 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>')


FYI : As @Reddy comment - 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.

like image 166
Pranav C Balan Avatar answered Sep 26 '22 15:09

Pranav C Balan