0


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

3
  • 1
    Could you provide an example of the dataset you are trying to parse, and the desired results? Commented Mar 11, 2011 at 22:45
  • I would but this comment block won't let me add returns. Commented Mar 11, 2011 at 22:58
  • You can edit your question and put it there. Commented Mar 11, 2011 at 23:08

3 Answers 3

2

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]];
}
Sign up to request clarification or add additional context in comments.

3 Comments

Although it's possible to do multidimensional arrays in javascript... wouldn't be more correct to use an object?
Yes, this loop will produce a two-dimensional array. Whether it makes more sense to store it as an array of arrays or an array of objects is too situational to cover in a short answer. :-)
Yeah ... that's the two-phase approach I was talking about ... was hoping for one ... but oh well ... thanks
0

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

Comments

0

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.

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.