【发布时间】:2019-06-29 01:47:45
【问题描述】:
我有一个多维数组。我想将其中的值分组并知道有多少。
我创建了一个新数组。我已经循环了一个多维数组。如果新数组中不存在当前值,则将此值添加到数组中。但是我不能动态地做,它们都被添加到了底部。我无法将其添加到“子类别”中。
这样我就有了一个多维数组。
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": []
}
]
}
]
}
]
}
【问题讨论】:
-
如果您“因为太复杂而不想添加代码”,如果它如此复杂,您希望我们如何添加它?
-
我不清楚你想要做什么和实现的目标
-
currentArray = [ [1, 2, 3, 5], [5, 3, 1, 2], [3, 1, 3, 1], ]时会发生什么 -
对不起。我已经添加了我的问题和我尝试过的解决方案。
标签: javascript typescript