javascript - 在没有递归的情况下展平多个嵌套数组的数组 - javascript

标签 javascript arrays flatten

也许这是个愚蠢的问题,但我无法意识到是否可以在不递归的情况下展平多维数组

我有一个用递归写的解决方案:

function transform (arr) {
   var result = [];
   arr.forEach(flatten)
   function flatten (el) {
     if (Array.isArray(el)) {
        return el.forEach(flatten);
     }
     return result.push(el);
   }
   return result;
}

要展平的数组示例:

[1, {a: [2, 3]}, 4, [5, [6]], [[7], 8, 9], 10]

和执行:

var a = [1, {a: [2, 3]}, 4, [5, [6]], [[7], 8, 9], 10];
var r = transform(r);
console.log(r); // [1, {a: [2, 3]}, 4, 5, 6, 7, 8, 9, 10]

谢谢!

最佳答案

您可以使用堆栈。当您发现嵌套数组时,只需将其替换为它的项即可。

function flatten(arr) {
  var result = [];
  var stack = arr, first;

  while (stack.length > 0) {
    first = stack[0];

    if (Array.isArray(first)) {
      // Replace the nested array with its items
      Array.prototype.splice.apply(stack, [0, 1].concat(first));
    } else {
      result.push(first);
      // Delete the first item
      stack.splice(0, 1);
    }
  }

  return result;
}

关于javascript - 在没有递归的情况下展平多个嵌套数组的数组 - javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27303369/

相关文章:

javascript - typescript 源解析 : get interface related to certain react class

javascript - 如何在另一个 Vue 项目中使用 Vue Web 组件(由 Vue-CLI 3 生成)?

javascript - Passport 自定义回调如何工作?

c++ - pArray = pArray + 1;有人可以向我解释这如何在 C++ 中增加数组吗?

php - 使用 SQL 数据创建数组或 json

c# - ISerializable 与递归 child

python - 将列表的多级列表展平为单级

python - 使用选择/忽略特定键来展平字典

javascript - 自定义拖放实现

Python:元组和单个 float 的高效展开/展平列表