4

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
}

3 Answers 3

7

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

Sign up to request clarification or add additional context in comments.

10 Comments

It would be best if the function would work correctly for any number of separators (not just one or two) - this would offer a greater amount of flexibility.
@AndersonGreen - for sure - it should be simple for you to generalize the above code into a function that accepts the delimiteres as parameters :)
Are there any other concise ways of representing multidimensional arrays in Javascript (besides this one)? I want to avoid "re-inventing the wheel", if possible.
To remove the space, you could also just split on '; ' the first time.
You can split on a regex. If you split by /\;\s*/g to begin with, you don't have to replace(/^\s*/, '') later.
|
1

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/

5 Comments

Did you test this? Because I'm fairly certain this doesn't work.
He's right. Even if you include a return strings in the function, it doesn't quite work jsfiddle.net/beTEq
@TomSarduy The function "getArray" returns undefined, but it should return the variable strings as well as printing it to the console. All you need to do now is add return strings; after the last line in the function getArray, so that it will work correctly.
@AndersonGreen: Yes, I forgot that, I was very focused in the console output
@TomSarduy Also, it appears that it won't work when there are more than two separators - it might be fairly easy to fix this, though.
0

I figured out a solution that can handle any number of separators, based on this answer here.

function getArray(theString, separators) {
    separators = separators.reverse();
    var theArray = theString.split(separators[0]);
    for (var j = 1; j < separators.length; j++) {
        theArray = theArray.map(function mapper(v, i, a) {
            if (typeof v == "string") {
                return v.split(separators[j]);
            } else {
                return v.map(mapper);
            }
        });
    }
    return theArray;
}

console.log(JSON.stringify(getArray("A, b, c; d, e, f;g,h,i'a, b, c;d,e,f", [",", ";", "'"])));
//this will write [[["A"," b"," c"],[" d"," e"," f"],["g","h","i"]],[["a"," b"," c"],["d","e","f"]]] to the console.

Comments

Your Answer

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.