簡體   English   中英

將多維數組轉換為一維數組

[英]Convert multidimensional array to one-dimensional array

我有一個多維數組。 我想將其中的值分組並知道有多少。

我創建了一個新數組。 我循環了一個多維數組。 如果新數組中不存在當前值,我會將此值添加到數組中。 但是我動態的不行,都加到了底部。 我無法將其添加到“子類別”。

這樣我就有了一個多維數組。

   currentArray = [
     [1, 2, 3, 5],
     [1, 2, 3, 4],
     [1, 2, 3, 4],
     [1, 2, 3, 4],
     [1, 2, 3, 4],
     [1, 2, 3, 4],
     [1, 2, 3, 4]
   ]

我使用了這樣的循環。

    newArray= [];
    for (let i = 0; i < currentArray.length; i++) {
          for (let k = 0; k < currentArray[i].length; k++) {
            let obj = { id: currentArray[i][k], subCategories: [] };
            let index = newCategories.findIndex(x => x.id === obj.id);
            if (index === -1) {
              if (k === 0) {
                newCategories.push(obj);
              }
            } else {
              newCategories[index].subCategories.push(obj);
            }
          }
        }

我使用了這樣的循環,但沒有得到成功的結果。 當前代碼中的邏輯錯誤,我無法弄清楚。

我希望數組中的相同元素只添加到新數組一次。 我想在最后一個元素中獲得“計數”。

所以我想要實現的輸出如下。

   {
     "id": 1,
     "subCategories": [
       {
         "id": 2,
         "subCategories": [
           {
             "id": 3,
             "subCategories": [
               {
                 "id": 5,
                 "count": 1,
                 "subCategories": []
               },
               {
                 "id": 4,
                 "count": 6,
                 "subCategories": []
               }
             ]
           }
         ]
       }
     ]
   }

您可以通過減少內部數組並查找想要的 id 來減少數組。

 var array = [[1, 2, 3, 5], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]], result = array .reduce((r, a) => { var o = a.reduce((p, id) => { var temp = p.subCategories.find(q => q.id === id); if (!temp) { p.subCategories.push(temp = { id, subCategories: [] }); } return temp; }, r); o.count = (o.count || 0) + 1; return r; }, { subCategories: [] }) .subCategories; console.log(result);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

這與您的風格相同,通過使用與內部格式匹配的起始對象並搜索項目以返回此對象以供下一級使用。

 var currentArray = [[1, 2, 3, 5], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]], newArray = [], temp, item; for (let i = 0; i < currentArray.length; i++) { temp = { subCategories: newArray }; for (let k = 0; k < currentArray[i].length; k++) { item = temp.subCategories.find(x => x.id === currentArray[i][k]); if (!item) { temp.subCategories.push(item = { id: currentArray[i][k], subCategories: [] }); } temp = item; } temp.count = (item.count || 0) + 1; } console.log(newArray);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

暫無
暫無

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

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