Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a JS multidimensional array from string

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?

like image 294
Victor Njoroge Avatar asked Feb 08 '23 22:02

Victor Njoroge


2 Answers

You could split it, but you have all the delimiters in place anyway, just rewrite your string to be JSON-conformant and run it through JSON.parse():

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

// quote text data. If the array was plain number data, we don't even need this step.
var quoted = str.replace(/([a-zA-Z]+)/g,'"$1"');

// rewrite to JSON form for a nested array
var jsonStr = "[[" + quoted.replace(/#/g,'],[') + "]]";

// done, just tell the JSON parser to do what it needs to do.
var arr = JSON.parse(jsonStr);

And that's it, arr is now the nested array [["A",2,5],["B",4,4],["C",4,4]].

like image 124
Mike 'Pomax' Kamermans Avatar answered Feb 11 '23 01:02

Mike 'Pomax' Kamermans


This should work

var str = "A,2,5# B,4,4# C,4,4";
var arr = str.split(/\s*\#\s*/g);
    for (var i = 0; i < arr.length; i++) {  
        arr[i]=arr[i].split(/\s*\,\s*/g);
    }
console.log(arr)

In your solution var arr2 = []; needs to be outside the for loop, or it gets redefined everytime. However, we don't really need to define a separate var and simply update the original array.

like image 24
mani Avatar answered Feb 11 '23 00:02

mani