展平奇数阵列结构javascript

时间:2014-05-21 13:48:41

标签: javascript arrays

可怕的嵌套数组:

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

我想要的魔术功能的输出:

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

到目前为止:

 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];
              };
            };

我明白了:

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

不错,但也没有。有什么想法吗?

1 个答案:

答案 0 :(得分:4)

首先让我们打印您的输入数组,这样我才能看到我正在做的事情。

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

好。所以基本上它是一棵树,你想要一个所有分支的数组。不应该太难......

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!",正如他们所说。