Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multidimensional array separators in Javascript

Tags:

javascript

I've been searching for a more concise way to represent multidimensional arrays in Javascript, so I'd like to find a way to separate an array using multiple separators, along with Javascript's built-in string.split(separator) method.

For example, the string "what, am, I; doing, here, now" would become [["what", "am", "I"],["doing", "here", "now"]].

Is there any concise way to implement a function that does this?

var theString = "what, am, I; doing, here, now";
var theArray = getArray(theString, [",", ";"]); //this should return [["what", "am", "I"],["doing", "here", "now"]].

function getArray(theString, separators){
    //convert a string to a multidimensional array, given a list of separators
}
like image 422
Anderson Green Avatar asked Feb 18 '23 05:02

Anderson Green


2 Answers

LAST EDIT

I was leaving some commas in the words, as @Tom points out. Here's the final code:

var str = "what, am, I; doing, here, now";

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

AND FIDDLE


First split on the second separator, then split each member in there on the other separator.

var str = "what, am, I; doing, here, now";

var arr = str.split(';');
for (var i = 0; i < arr.length; i++){
    arr[i] = arr[i].split(' ');
}

LIVE DEMO

Note that you'll have to do a tad bit of cleanup to remove the empty space in the second array, but that should be simple.


EDIT -- I was feeling energetic - here's how you kill that annoying leading space

var str = "what, am, I; doing, here, now";

var arr = str.split(';');
for (var i = 0; i < arr.length; i++){
    arr[i] = arr[i].replace(/^\s*/, '').split(' ');
}

UPDATED FIDDLE


EDIT - this is why I love SO so much. Per @Nathan, you can just split on the regex and save some trouble

var str = "what, am, I; doing, here, now";

var arr = str.split(/\;\s*/g);
for (var i = 0; i < arr.length; i++){
    arr[i] = arr[i].split(' ');
}
console.log(arr);

UPDATED FIDDLE

like image 146
Adam Rackis Avatar answered Feb 21 '23 02:02

Adam Rackis


This should work:

var theString = "what, am, I; another, string; doing, here, now";
 //this should return [["what", "am", "I"],["doing", "here", "now"]].

function getArray(theString, separators){
    //Firs split
    var strings = theString.replace(/\s+/g, '').split(separators.pop());
    //Second split
        var sep = separators.pop();
        for (var i = 0; i < strings.length; i++) {
            strings[i] = strings[i].split(sep);
        };
    console.log(strings);
    return strings;
}

var theArray = getArray(theString,["," ,";" ]);

Update:

Now the code should work: http://jsfiddle.net/beTEq/1/

like image 21
Tom Sarduy Avatar answered Feb 21 '23 01:02

Tom Sarduy