Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a dynamically filled variable containing numbers formatted as text that are separated by commas.

When alerting this out for testing I get something like: var myVar = 3,5,1,0,7,5

How can I convert this variable into a valid JavaScript or jQuery array containing integers ?

I tried $.makeArray(myVar) but that doesnt work.

Thanks for any help with this, Tim.

share|improve this question
add comment

2 Answers

up vote 3 down vote accepted

Simple, try this.

var myVar = 3,5,1,0,7,5;
myVarArray = myVar.split(",");

// Convert into integers 
for(var i=0, len = myVarArray.len; I < len; I++){
  myVarArray[i] = parseInt(myVarArray[i], 10);
}
// myVarArray is array of integers 
share|improve this answer
1  
Thanks very much - this looks great. Can you explain what the ", 10" does ? –  user2571510 13 hours ago
2  
@user2571510 you can get complete doc for parseInt from developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… –  Anoop 13 hours ago
    
I see - thanks again ! I will accept as soon as I can. –  user2571510 13 hours ago
    
@user2571510, check out my answer too –  Amit Joki 13 hours ago
add comment

You can just do this:

var myVar = "3,5,1,0,7,5"; 
var myArr = myVar.split(',').map(function(x){return +x});

myArr will have integer array.

I changed myVar = 3,5,1,0,7,5 to myVar = "3,5,1,0,7,5" because the former wasn't valid.

I presume that it is a string.

share|improve this answer
    
Thanks. This is very helpful too. –  user2571510 13 hours ago
    
@user2571510, this myVar = 3,5,1,0,7,5 is not valid. –  Amit Joki 13 hours ago
1  
It works for me. Just copy paste my answer in your browser console and you'll see the result –  Amit Joki 13 hours ago
1  
No. You don't have to do anything except copying my answer as it is. –  Amit Joki 13 hours ago
1  
Take a look: jsfiddle.net/AmitJoki/279BX –  Amit Joki 12 hours ago
show 11 more comments

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.