从嵌套数组中提取子数组

mho*_*ges 12 javascript arrays recursion

我有嵌套数组数据,我想提取所有嵌套数组作为其父级的兄弟.我非常接近,但我在结果中得到一个额外的空数组,我无法弄清楚它来自何处或如何摆脱它.

注意:我真的很想了解为什么会发生这种情况以及如何在我的函数中摆脱它,而不仅仅是.filter(arr => arr.length)在我的结果列表中.

这是我到目前为止的尝试:

var arrs = [
  [1, 2, [3, 4], 5],
  [6, [7, 8, 9, [10, 11]]],
  [12, 13],
  [[14, 15], [16, 17]],
  [[1], 4, [1, 1], 4]
];

// Desired Output
// [
//   [1, 2, 5],
//   [3, 4],
//   [6],
//   [7, 8, 9],
//   [10, 11],
//   [12, 13],
//   [14, 15],
//   [16, 17],
//   [4, 4]
//   [1]
//   [1, 1]
// ]

function extractArrays (arr) {
  return arr.reduce((res, curr) => {
    if (Array.isArray(curr)) {
      res = res.concat(extractArrays(curr));
    }
    else {
      res[0].push(curr);
    }
    return res;
  }, [[]]);
}

console.log(extractArrays(arrs));
// Results:
// [ 
//   [],  <-- Where is this coming from?
//   [ 1, 2, 5 ],
//   [ 3, 4 ],
//   [ 6 ],
//   [ 7, 8, 9 ],
//   [ 10, 11 ],
//   [ 12, 13 ],
//   [],  <-- Also here
//   [ 14, 15 ],
//   [ 16, 17 ],
//   [ 4, 4 ],
//   [ 1 ],
//   [ 1, 1 ]
// ]
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper {
  max-height: 100% !important;
}
Run Code Online (Sandbox Code Playgroud)

Awa*_*yte 5

元素 like[[14, 15], [16, 17]]会引入一个[]after 递归。这应该通过检查长度来处理。

var arrs = [
  [1, 2, [3, 4], 5],
  [6, [7, 8, 9, [10, 11]]],
  [12, 13],
  [[14, 15], [16, 17]],
  [[1], 4, [1, 1], 4]
];

function extractArrays (arr, acc=[]) {
  if (arr.length == 0 ) return acc;
  let pure = arr.filter(elm => !Array.isArray(elm));
  if (pure.length > 0) {
    acc.push(pure);
  }
    
  acc.concat(arr.filter(elm => Array.isArray(elm)).map(elm => extractArrays(elm, acc)));

  return acc;
}

console.log(extractArrays(arrs));
Run Code Online (Sandbox Code Playgroud)