Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert array of string javascript to array of integer javascript

I have an array,

var array = ["1","2","3","4","5"];

then I need to convert to

var array = [1,2,3,4,5];

How can i convert?

like image 842
Khoerodin Avatar asked Sep 02 '26 04:09

Khoerodin


2 Answers

Map it to the Number function:

var array = ["1", "2", "3", "4", "5"];
array = array.map(Number);
array; // [1, 2, 3, 4, 5]
like image 55
Sebastian Simon Avatar answered Sep 03 '26 17:09

Sebastian Simon


The map() method creates a new array with the results of calling a provided function on every element in this array.

The unary + acts more like parseFloat since it also accepts decimals.

Refer this

Try this snippet:

var array = ["1", "2", "3", "4", "5"];
array = array.map(function(item) {
  return +item;
});
console.log(array);
like image 44
Rayon Avatar answered Sep 03 '26 18:09

Rayon