1

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 doesn't work.

halfer
20.2k20 gold badges111 silver badges208 bronze badges
asked Apr 12, 2014 at 12:17

2 Answers 2

3

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 
Ram
145k16 gold badges174 silver badges201 bronze badges
answered Apr 12, 2014 at 12:20
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks very much - this looks great. Can you explain what the ", 10" does ?
@user2571510 you can get complete doc for parseInt from developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
I see - thanks again ! I will accept as soon as I can.
@user2571510, check out my answer too
1

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.

answered Apr 12, 2014 at 12:25

12 Comments

@user2571510, this myVar = 3,5,1,0,7,5 is not valid.
I checked on this but it doesnt seem to work for me: myArr is empty in this case.
It works for me. Just copy paste my answer in your browser console and you'll see the result
Do I have to declare myArr as an array before ?
No. You don't have to do anything except copying my answer as it is.
|

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.