【发布时间】:2020-05-30 13:49:43
【问题描述】:
我有一个这样的数组:[1, 2, 3, 4, 5, 6, 7, 9, 10]。我需要将它分成不同大小的块,但使用一个简单的模式:4、3、3、3、4、3、3、3,如下所示:
[
[ // four
1,
2,
3,
4
],
[ // three (1/3)
5,
6,
7
],
[ // three (2/3)
8,
9,
10
],
[ // three (3/3)
11,
12,
13
],
[ // four
14,
15,
16,
17
],
[ // three (1/3)
18,
19,
20
], // and so on..
]
我已经尝试使用我自定义的这段代码:
const arr; // my array of values
const chuncked = arr.reduce((acc, product, i) => {
if (i % 3) {
return acc;
} else if (!didFourWayReduce) {
didFourWayReduce = true;
fourWayReduces++;
if ((fourWayReduces - 1) % 2) { // only make every second a "4 row"
return [...acc, arr.slice(i, i + 3)];
} else {
return [...acc, arr.slice(i, i + 4)];
}
} else {
didFourWayReduce = false;
return [...acc, arr.slice(i, i + 3)];
}
}, []);
并且它几乎可以工作,期望第一个三块(1/3)具有该块的最后一个元素为 4。因此,每三个的第一个块重复 1 个键。像这样:
[
[
1,
2,
3,
4
],
[
4, // this one is repeated, and it shouldn't be
5,
6
]
]
【问题讨论】:
标签: javascript arrays multidimensional-array ecmascript-6 reduce