首页 > 解决方案 > 如何仅展平/减少第 N 维数组的最深或其他指定级别

问题描述

假设一个 N 维数组,例如。

const array = [
  "1",
  ["2","2"],
  [["3","3"],["3","3"]],
  [
    [
      [["4","4"],"3"],
      [["4","4"],"3"]
    ],
  ],
  [["3","3"],["3","3"]],
  ["2","2"],
  "1"
];

我只能找到从索引的浅端向上展平数组的方法,但我需要展平/减少或仅处理最深(或任何任意)索引级别。

当运行最深的级别时,我正在寻找一个数组输出沿线的东西

array = [
  "1",
  ["2","2"],
  [["3","3"],["3","3"]],
  [
    [
      ["4,4","3"],
      ["4,4","3"]
    ],
  ],
  [["3","3"],["3","3"]],
  ["2","2"],
  "1"
];

我找不到不是垃圾的解决方案......(过于复杂/令人难以置信的混乱)任何帮助将不胜感激

标签: javascriptarraysmultidimensional-arrayflatten

解决方案


You could create a function that will take the data and level that you want to flatten and will flatten only that level. Then to get the last level you can create another function.

const array = ["1",["2","2"],[["3","3"],["3","3"]],[[[["4","4"],"3"],[["4","4"],"3"]],[["",""],["",""]]],[["3","3"],["3","3"]],["2","2"],"1"];

function lastLvl(data, lvl = 0) {
  return data.reduce((r, e) => {
    if (lvl > r) r = lvl

    if (Array.isArray(e)) {
      const nlvl = lastLvl(e, lvl + 1);
      if (nlvl > r) r = nlvl
    }

    return r
  }, 0)
}

function flattenLvl(data, lvl, clvl = 1) {
  return data.reduce((r, e) => {
    if (Array.isArray(e)) {
      const nested = flattenLvl(e, lvl, clvl + 1);
      if (clvl == lvl) r.push(...nested);
      else r.push(nested)
    } else {
      r.push(e)
    }

    return r;
  }, [])
}

const lvl = lastLvl(array)
const result = flattenLvl(array, lvl)
console.log(result)


推荐阅读