Xi Vix
Xi Vix

Reputation: 1361

how to load two dimensional array in javascript


I have a string containing many lines of the following format:
<word1><101>
<word2><102>
<word3><103>
I know how to load each line into an array cell using this:

var arrayOfStuff = stringOfStuff.split("\n");  

But the above makes one array cell per line, I need a two-dimensional array. Is there a way to do that using similar logic to the above without having to re-read and re-process the array. I know how to do it in two phases, but would rather do it all in one step.
Thanks in advance,
Cliff

Upvotes: 0

Views: 1100

Answers (3)

Mike Samuel
Mike Samuel

Reputation: 120506

If you wanted to parse a CSV for example, you can do

var parsedStuff = [];
stringOfStuff.replace(/\r\n/g, '\n')  // Normalize newlines
    // Parse lines and dump them in parsedStuff.
    .replace(/.*/g, function (_) { parsedStuff.push(_ ? _.split(/,/g)) : []; })

Running

stringOfStuff = 'foo,bar\n\nbaz,boo,boo'
var parsedStuff = [];
stringOfStuff.replace(/\r\n/g, '\n')
    .replace(/.*/g, function (_) { parsedStuff.push(_ ? _.split(/,/g)) : []; })
JSON.stringify(parsedStuff);

outputs

[["foo","bar"],[],["baz","boo","boo"]]

You can adjust the /,/ to suite whatever record separator you use.

Upvotes: 0

Ben Blank
Ben Blank

Reputation: 56572

It sounds like you're hoping for something like Python's list comprehension (e.g. [line.split(" ") for line in lines.split("\n")]), but Javascript has no such feature. The very simplest way to get the same result in Javascript is to use a loop:

var lines = lines.split("\n");

for (var i = 0; i < lines.length; i++) {
    lines[i] = lines[i].split(" ");

    // or alternatively, something more complex using regexes:
    var match = /<([^>]+)><([^>]+)>/.exec(lines[i]);
    lines[i] = [match[1], match[2]];
}

Upvotes: 2

Martin Jespersen
Martin Jespersen

Reputation: 26183

Not really. There are no native javascript functions that return a two-dimensional array.

Upvotes: 0

Related Questions