2015-06-02 133 views
0

我想获取嵌套数组中的所有子数组,包括每个深度(包括原始输入数组)的新数组,并将它们放入一个新数组中。JS - 将嵌套数组分为一个包含数组

输入:

var array = ["cat", ["dog", ["rabbit"]], "hamster"] 

输出:

newArray = [ 
      ["cat", ["dog", ["rabbit"]], "hamster"], 
      ["dog", ["rabbit"]], 
      ["rabbit"] 
      ] 

尝试:

var unnest = function(array) { 
    var container = [array]; 
    for (var i in array) { 
     if (array[i] instanceof Array) { 
      container.push(array[i]); 
     } 
    } 
    return container 
} 

我知道这需要某种形式的迭代或递归的过程,但是这就是我卡住了(我是JavaScript新手)。谢谢。

+1

那么你有什么尝试呢? – Oka

+0

@Oka对不起,只是添加了我的尝试解决方案。 – ChrisG7891

回答

0

你很近!只有一件事需要改变:将你的for循环包装在一个函数中,这样你可以递归地调用它。这是一种做法。

var unnest = function(array) { 
    var container = [array]; 

    var collectNestedArrays = function(array) { 
    array.forEach(function(x) { 
     if (x instanceof Array) { 
     container.push(x); 
     collectNestedArrays(x); 
     } 
    }); 
    }; 

    collectNestedArrays(array); 

    return container; 
}; 
+0

谢谢@troyastorino。当它涉及到递归部分时,我碰壁了,但这有很大帮助。 – ChrisG7891

0

因为我们遍历数组并创建父阵列和树中的每个子数组元素,这是一个问题达是最好用递归算法DFS解决。

function unnest(src) { 
    // overload the parameters and take the target array as a second argument. 
    // this helps us avoid having nested functions, improve performance 
    // and reduce boilerplate 
    var target = arguments[1] || []; 

    // add the current array to the target array 
    target.push(src); 

    // iterate on the parent array and recursively call our function, 
    // assigning the child array, and the target array as function parameters 
    src.forEach(function (node) { 
    if (node instanceof Array) { 
     unnest(node, target); 
    } 
    }); 
    return target; 
} 
+0

好的答案提供了对代码的解释 –

0

这是一个递归实现。

var unNest = function(array) { 
    // Create a results array to store your new array 
    var resultsArr = []; 
    // Recursive function that accepts an array 
    var recurse = function(array) { 
    // Push the passed-in array to our results array 
    resultsArr.push(array); 
    // Iterate over the passed-in array 
    for (var i = 0; i < array.length; i++) { 
     // If an element of this array happens to also be an array, 
     if (Array.isArray(array[i])) { 
     // Run the recursive function, passing in that specific element which happens to be an array 
     recurse(array[i]); 
     } 
    } 
    } 
    // Invoke our recurse function, passing in the original array that unNest takes in 
    recurse(array); 
    // Return the results array 
    return resultsArr; 
} 
+0

啊这很清楚。感谢您的代码中的评论。这有助于达成巨大的交易。 – ChrisG7891

+0

很高兴你发现它有帮助! –