JS - 将嵌套数组分隔为包含的数组

时间:2015-06-02 04:28:58

标签: javascript arrays

我想将所有子数组放在嵌套数组中,从每个深度(包括原始输入数组)中创建一个新数组,并将它们放入一个新数组中。

输入:

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的新手)。感谢。

3 个答案:

答案 0 :(得分: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;
};

答案 1 :(得分: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;
}

答案 2 :(得分: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;
}