亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將多維數組轉換為二維數組?

如何將多維數組轉換為二維數組?

蝴蝶刀刀 2023-08-24 18:03:23
給定多維數組(任意大小和深度):const multidimensionalArray = [1, [2, [3, [4, [5]]]], [6], [7, [8], [9]]];我需要按照下面的示例將其轉換為二維數組(其想法是每個嵌套值應轉換為所有父項 + 該值的數組)。預期的二維數組:const twoDimensionsArray = [  [1],  [1, 2],  [1, 2, 3],  [1, 2, 3, 4],  [1, 2, 3, 4, 5],  [1, 6],  [1, 7],  [1, 7, 8],  [1, 7, 9],];你能幫我解決這個問題嗎?
查看完整描述

1 回答

?
慕俠2389804

TA貢獻1719條經驗 獲得超6個贊

對每個嵌套數組的遞歸調用應該可以解決問題。

注意:以下內容對于您的用例來說可能并不完整 - 您的數據需要按特定順序才能工作 - 但我認為作為示例,這應該足夠干凈:

const customFlatten = (arr, parents = [], output = []) => {

? for (const item of arr) {

? ? // If not an array...

? ? if (!Array.isArray(item)) {

? ? ? parents.push(item) // update parents for recursive calls

? ? ? output.push(parents.slice(0)) // add entry to output (copy of _parents)


? ? // If an array...

? ? } else {

? ? ? customFlatten(item, parents.slice(0), output) // recursive call

? ? }

? }

? return output

}


console.log(customFlatten([1, [2, [3, [4, [5]]]], [6], [7, [8], [9]]]))


查看完整回答
反對 回復 2023-08-24
  • 1 回答
  • 0 關注
  • 197 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號