How to convert all elements in an array to integer in JavaScript?

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


var arr = ["1", "2", "3"];
arr = arr.map(Number);
console.log(arr); // [1, 2, 3]

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

Tags:

Javascript