Ad

Create A JS Multidimensional Array From String

- 1 answer

I would like to create a miltidimentional array as follows so

var multi-arr = [
                  ["A,2,5"], 
                  ["B,4,4"], 
                  ["C,4,4"]
                ]

from string values gotten from the database using ajax.

string data gotten from db delimited by #

var string = "A,2,5# B,4,4# C,4,4";

I split the string by a '#' delimiter

arr1=string.split(/\s*\#\s*/g);

creating the array below

var arr = ["A,2,5", "B,4,4", "C,4,4"];

I want to further split the items in the above array using the comma ',' as a delimiter and create a multidimensional array

My problem is the loop only pushes in the last item in the array

for (i = 0; i < arr.length; i++) {  
        var arr2 = [];
        arr2[i]=arr2.push(arr1[i].split(/\s*\,\s*/g));
    }

console.log(arr2);

What am i doing wrong? or what can i do better?

Ad

Answer

The var statement should be outside the for loop and you don't need to do the assignment and the push.

var i;
var string = "A,2,5# B,4,4# C,4,4";
var arr1 = string.split("#");
var arr2 = [];
for (i = 0; i < arr1.length; i++) {
        arr2[i]=arr1[i].split(",");
}   

console.log(arr2);

As suggested by Mike 'Pomax' - you could return the data from the server as JSON. If you're using PHP, that can be done like so:

header('Content-Type: application/json');
echo json_encode($queryResult);
exit;
Ad
source: stackoverflow.com
Ad