【问题标题】:JS - Separate nested arrays into a contained arrayJS - 将嵌套数组分离成一个包含的数组
【发布时间】:2026-01-01 09:15:02
【问题描述】:

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

输入:

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

【问题讨论】:

  • 那你有什么尝试?
  • @Oka 抱歉,刚刚添加了我尝试的解决方案。

标签: javascript arrays


【解决方案1】:

这是一个递归实现。

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

【讨论】:

  • 啊这很清楚。感谢您的代码中的 cmets。这有很大帮助。
  • 很高兴您发现它有帮助!
【解决方案2】:

你已经接近了!你只需要改变一件事:将你的 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;
};

【讨论】:

  • 谢谢你,@troyastorino。当涉及到递归部分时,我碰壁了,但这很有帮助。
【解决方案3】:

因为我们迭代一个数组并为父数组和树中的每个子数组创建元素,这是一个最好用递归 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;
}

【讨论】: