Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant way to convert string of values into a Javascript array?

I have an ajax request that returns a list of values like this:

"1,2,3,4,5,6"

I need it to be a javascript array with numbers:

[1,2,3,4,5,6]

I tried:

var array = new Array("1,2,3,4,5,6".split(","))

But the numbers are still strings in the output:

["1","2","3","4","5","6"]

Is there a clean way to have it as a numbered array? Preferably without writing a function to iterate through it?

like image 750
kush Avatar asked Jan 03 '11 23:01

kush


2 Answers

You need to loop through and convert them to numbers, like this:

var array = "1,2,3,4,5,6".split(",");
for(var i=0; i<array.length; i++) array[i] = +array[i];

Or, the more traditional example:

var array = "1,2,3,4,5,6".split(",");
for(var i=0; i<array.length; i++) array[i] = parseInt(array[i], 10);
like image 125
Nick Craver Avatar answered Sep 27 '22 22:09

Nick Craver


A more jQuery-centric approach using jQuery.map():

var str = "1,2,3,4,5,6";
var arr = $.map(str.split(","), function(el) { return parseInt(el, 10); });
like image 28
Andrew Whitaker Avatar answered Sep 27 '22 22:09

Andrew Whitaker