首页 > 解决方案 > 将多维数组转换为一维数组

问题描述

我有一个多维数组。我想将其中的值分组并知道有多少。

我创建了一个新数组。我已经循环了一个多维数组。如果新数组中不存在当前值,我将这个值添加到数组中。但我不能动态地做,它们都被添加到底部。我无法将其添加到“子类别”中。

这样我就有了一个多维数组。

   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": []
               }
             ]
           }
         ]
       }
     ]
   }

标签: javascripttypescript

解决方案


您可以通过减少内部数组来减少数组并寻找想要的 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; }


推荐阅读