0

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?

3 Answers 3

5

"...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/


Sign up to request clarification or add additional context in comments.

3 Comments

+1 for .map(Number). It might be useful to add browser support info (for example no support for IE7 / IE8)
@jenson-button-event: Has better support than items.Skip(1).Cast<int>() :P
@jen: Heh, "pig-headed"... OINK!
1

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

1 Comment

In fact, if you know they're all strings then you might as well omit the typeof check.
1

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)

Comments

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.