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?
2 Answers 2
Map it to the Number function:
var array = ["1", "2", "3", "4", "5"];
array = array.map(Number);
array; // [1, 2, 3, 4, 5]
answered Oct 6, 2015 at 8:03
Sebastian Simon
19.8k8 gold badges61 silver badges88 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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);
answered Oct 6, 2015 at 8:01
Rayon
36.6k5 gold badges54 silver badges78 bronze badges
4 Comments
amdixon
good answer, but whats the point of the snippet which expands to nothing ?
Andreas
@amdixon Just open the console (F12) of your browser ;)
amdixon
point taken - it is just slightly faster than copy+pasting it into the console ;)
Sebastian Simon
The unary plus converts things into a number, just like the unary minus converts it into a number and negates it.
lang-js