Apollo Apollo - 1 year ago 99
Javascript Question

Removing quotes from each string in an array - Javascript

I've searched here: http://w3schools.com/jsref/default.asp but could not find any convenience method to perform this function. If I have an array

var arrayOfStrings = ["20","10","30","100"]
, is there a quick way to remove all quotes (") from each string in this array without having to loop through?

I essentially want to create this:
var arrayOfNumbers = [20,10,30,100]


Answer Source

If you want number conversion, you can do it like this...

var arrayOfNumbers = arrayOfStrings.map(Number);

The .map() method creates a new array populated with the return value of the function you provide.

Since the built-in Number function takes the first argument given and converts it to a primitive number, it's very usable as the callback for .map(). Note that it will interpret hexadecimal notation as a valid number.

Another built-in function that would accomplish the same thing as the callback is parseFloat.

var arrayOfNumbers = arrayOfStrings.map(parseFloat)

The parseInt function however will not work since .map() also passes the current index of each member to the callback, and parseInt will try to use that number as the radix parameter.

DEMO: http://jsfiddle.net/UDWvH/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download