Uzer
Uzer

Reputation: 3190

Flattening odd array structure javascript

Horrible nested array:

x=[0,[1,[2,[3,[4,["five"],[5]]]],["to",["free",["floor"]]],["two",["three",["four"]]]]]

Output of the magic function that I would like:

magic(x)=>[[0,1,2,3,4,"five"],[0,1,2,3,4,5],[0,1,"to","free","floor"],[0,1,"two","three","four"]]

So far with:

 magic(x)==>
 this.unpack_gret = function(strut){
                var lenstruc = strut.length;
                var firstelem = strut.shift();
                if (lenstruc > 1){

                    var maprecur = strut.map(function(item){
                        var retrecur = [firstelem].concat(this.unpack_gret(item))
                        return retrecur
                    });
                    if (maprecur.length > 1){return maprecur}
                    else {return maprecur[0];}

                }
                else {
                    return [firstelem];
              };
            };

I get:

[0,[1,2,3,[4,"five"],[4,5]],[1,"to","free","floor"],[1,"two","three","four"]]

Not bad but not there either. Any ideas?

Upvotes: 4

Views: 119

Answers (1)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324630

First let's pretty-print your input array, just so I can see what I'm doing.

x =
[
  0,
  [
    1,
    [
      2,
      [
        3,
        [
          4,
          ["five"],
          [5]
        ]
      ]
    ],
    [
      "to",
      [
        "free",
        ["floor"]
      ]
    ],
    [
      "two",
      [
        "three",
        ["four"]
      ]
    ]
  ]
]

Okay. so basically it's a tree and you want an array of all the branches. Shouldn't be too hard...

function branchify(arr,branch,found) {
    branch = branch || [];
    found = found || [];

    var leaf = arr.shift();
    branch.push(leaf);
    if( arr.length == 0) {
        found.push(branch);
    }
    else {
        arr.forEach(function(path) {
            branchify(path,branch.slice(0),found);
        });
    }
    return found;
}
var result = branchify(x);

Demonstration

"Ta-da!", as they say.

Upvotes: 4

Related Questions