user1180997
user1180997

Reputation: 103

Change array values to number from string

I have an array with these values:

var items = [Thursday,100,100,100,100,100,100]

I'm grabbing these from the URL query string so they are all string values. I want all columns except the first to be number. The array may vary in the number of columns, so is there a way to set this so items[0] is always a string, but items[n] is always a number?

Upvotes: 0

Views: 142

Answers (3)

user1106925
user1106925

Reputation:

"...is there a way to set this so items[0] is always a string, but items[n] is always a number?"

Use .shift() to get the first, .map() to build a new Array of Numbers, then .unshift() to add the first back in.

var first = items.shift();
items = items.map(Number);
items.unshift(first);

DEMO: http://jsfiddle.net/EcuJu/


We can squeeze it down a bit like this:

var first = items.shift();
(items = items.map(Number)).unshift(first);

DEMO: http://jsfiddle.net/EcuJu/1/


Upvotes: 5

Christophe
Christophe

Reputation: 28114

parseFloat() will convert your string to a number.

Here is a sample code for modern browsers (won't work in IE7/IE8):

var convertedItems=items.map(function(element,index){
  // Convert array elements with index > 0
  return (index>0)?parseFloat(element):element;
});

There's also a parseInt() method for conversion to integers:

parseInt(element,10)

Upvotes: 1

Klors
Klors

Reputation: 2674

I think this should work for you. You could set whatever default number you liked instead of 0.

var items = ["Thursday","100","100","100","100","100","100"], i;
for (i = 1; i < items.length; i++)
{
    if(typeof items[i] !== "number")
    {
        items[i] = isNaN(parseInt(items[i], 10)) ? 0 : parseInt(items[i], 10);
    }
}

Upvotes: 1

Related Questions