2

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

12

Map it to the Number function:

var array = ["1", "2", "3", "4", "5"];
array = array.map(Number);
array; // [1, 2, 3, 4, 5]
Sign up to request clarification or add additional context in comments.

Comments

6

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

4 Comments

good answer, but whats the point of the snippet which expands to nothing ?
@amdixon Just open the console (F12) of your browser ;)
point taken - it is just slightly faster than copy+pasting it into the console ;)
The unary plus converts things into a number, just like the unary minus converts it into a number and negates it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.