Use map() and parseInt()
Copyvar res = ['2', '10', '11'].map(function(v) {
return parseInt(v, 10);
});
document.write('<pre>' + JSON.stringify(res, null, 3) + '<pre>')
Run code snippetEdit code snippet Hide Results Copy to answer Expand
More simplified ES6 arrow function
Copyvar res = ['2', '10', '11'].map(v => parseInt(v, 10));
document.write('<pre>' + JSON.stringify(res, null, 3) + '<pre>')
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Or using Number
Copyvar res = ['2', '10', '11'].map(Number);
document.write('<pre>' + JSON.stringify(res, null, 3) + '<pre>')
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Or adding
+ symbol will be much simpler idea which parse the string
Copyvar res = ['2', '10', '11'].map(v => +v );
document.write('<pre>' + JSON.stringify(res, null, 3) + '<pre>')
Run code snippetEdit code snippet Hide Results Copy to answer Expand
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.
Answer from Pranav C Balan on Stack OverflowUse map() and parseInt()
Copyvar res = ['2', '10', '11'].map(function(v) {
return parseInt(v, 10);
});
document.write('<pre>' + JSON.stringify(res, null, 3) + '<pre>')
Run code snippetEdit code snippet Hide Results Copy to answer Expand
More simplified ES6 arrow function
Copyvar res = ['2', '10', '11'].map(v => parseInt(v, 10));
document.write('<pre>' + JSON.stringify(res, null, 3) + '<pre>')
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Or using Number
Copyvar res = ['2', '10', '11'].map(Number);
document.write('<pre>' + JSON.stringify(res, null, 3) + '<pre>')
Run code snippetEdit code snippet Hide Results Copy to answer Expand
Or adding
+ symbol will be much simpler idea which parse the string
Copyvar res = ['2', '10', '11'].map(v => +v );
document.write('<pre>' + JSON.stringify(res, null, 3) + '<pre>')
Run code snippetEdit code snippet Hide Results Copy to answer Expand
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.
You can simply use the Number object.
Copyḷet res = ['2', '10', '11'].map(Number);
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.
javascript - convert string into array of integers - Stack Overflow
How to convert all elements in an array to integer in JavaScript? - Stack Overflow
integer - Javascript string to int array - Stack Overflow
How can I convert a string to an integer in JavaScript? - Stack Overflow
Videos
You can use map and pass the String constructor as a function, which will turn each number into a string:
sphValues.map(String) //=> ['1','2','3','4','5']
This will not mutate sphValues. It will return a new array.
just by using array methods
var sphValues = [1,2,3,4,5]; // [1,2,3,4,5]
sphValues.join().split(',') // ["1", "2", "3", "4", "5"]
A quick one for modern browsers:
'14 2'.split(' ').map(Number);
// [14, 2]`
You can .split() to get an array of strings, then loop through to convert them to numbers, like this:
var myArray = "14 2".split(" ");
for(var i=0; i<myArray.length; i++) { myArray[i] = +myArray[i]; }
//use myArray, it's an array of numbers
The +myArray[i] is just a quick way to do the number conversion, if you're sure they're integers you can just do:
for(var i=0; i<myArray.length; i++) { myArray[i] = parseInt(myArray[i], 10); }
ECMAScript5 provides a map method for Arrays, 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()
You can do
var arrayOfNumbers = arrayOfStrings.map(Number);
- MDN Array.prototype.map
For older browsers which do not support Array.map, you can use Underscore
var arrayOfNumbers = _.map(arrayOfStrings, Number);
The simplest way would be to use the native Number function:
var x = Number("1000")
If that doesn't work for you, then there are the parseInt, unary plus, parseFloat with floor, and Math.round methods.
parseInt()
var x = parseInt("1000", 10); // You want to use radix 10
// So you get a decimal number even with a leading 0 and an old browser ([IE8, Firefox 20, Chrome 22 and older][1])
Unary plus
If your string is already in the form of an integer:
var x = +"1000";
floor()
If your string is or might be a float and you want an integer:
var x = Math.floor("1000.01"); // floor() automatically converts string to number
Or, if you're going to be using Math.floor several times:
var floor = Math.floor;
var x = floor("1000.01");
parseFloat()
If you're the type who forgets to put the radix in when you call parseInt, you can use parseFloat and round it however you like. Here I use floor.
var floor = Math.floor;
var x = floor(parseFloat("1000.01"));
round()
Interestingly, Math.round (like Math.floor) will do a string to number conversion, so if you want the number rounded (or if you have an integer in the string), this is a great way, maybe my favorite:
var round = Math.round;
var x = round("1000"); // Equivalent to round("1000", 0)
Try parseInt function:
var number = parseInt("10");
But there is a problem. If you try to convert "010" using parseInt function, it detects as octal number, and will return number 8. So, you need to specify a radix (from 2 to 36). In this case base 10.
parseInt(string, radix)
Example:
var result = parseInt("010", 10) == 10; // Returns true
var result = parseInt("010") == 10; // Returns false
Note that parseInt ignores bad data after parsing anything valid.
This guid will parse as 51:
var result = parseInt('51e3daf6-b521-446a-9f5b-a1bb4d8bac36', 10) == 51; // Returns true