Smoothing the structure of an odd javascript array

Awful nested array:

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

The output of the magic function that I need:

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 so. Any ideas?

+4
source share
1 answer

First let me pretty print your input array so that I can see what I'm doing.

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

Good. so basically it is a tree and you need an array of all branches. It 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

“Yes!” As they say.

+4
source

Source: https://habr.com/ru/post/1541428/


All Articles