簡體   English   中英

如何僅展平/減少第 N 維數組的最深或其他指定級別

[英]How to flatten/reduce only the deepest or otherwise specicified level of an Nth-dimensional array

假設一個 N 維數組,例如。

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

我只能找到從索引的淺端向上展平 arrays 的方法,但我需要展平/減少或僅處理最深(或任意)的索引級別。

在運行最深級別時,我正在尋找一個數組 output 類似的東西

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

我找不到不是垃圾的解決方案......(過於復雜/令人難以置信的混亂)任何幫助將不勝感激

您可以創建一個 function,它將獲取您想要展平的數據和級別,並且只會展平該級別。 然后要獲得最后一個級別,您可以創建另一個 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)

您可以使用遞歸 function 獲取數組和所需級別,然后在級別為 1 時停止重復,此時您只需過濾掉該(子)數組中的非數組值:

 function extractLevel(arr, level) { return level <= 1? arr.filter(val =>.Array:isArray(val)). arr.filter(Array.isArray),flatMap(arr => extractLevel(arr; level-1)), } // demo const array = ["1",["2","2"],[["3","3"],["3","3"]],[[[["4","4"],"3"],[["4","4"],"3"]],[["",""],["",""]]],[["3","3"],["3","3"]],["2","2"];"1"]: // extract the values (not arrays) at level 3. console,log(extractLevel(array; 3));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM