我有一个类似这样的数组:[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
]
]
发布于 2020-02-14 18:38:54
您可以使用两个索引,一个用于数据数组,另一个用于大小。然后用给定的长度分割数组,并将块推到块数组中。
继续进行直到数据结束。
var data = Array.from({ length: 26 }, (_, i) => i + 1),
sizes = [4, 3, 3, 3],
i = 0,
j = 0,
chunks = [];
while (i < data.length) chunks.push(data.slice(i, i += sizes[j++ % sizes.length]));
console.log(chunks);
.as-console-wrapper { max-height: 100% !important; top: 0; }
发布于 2020-02-14 18:45:15
const arr = Array.from({ length: 100 }, (_, i) => i);
const copy = [...arr];
const sizes = [4, 3, 3, 3];
const result = [];
let i = 0;
while (i <= arr.length && copy.length) {
result.push(copy.splice(0, sizes[i % sizes.length]));
i++;
}
console.log(result);
发布于 2020-02-14 19:16:08
递归方法相当优雅:
const chunks = (xs, [s, ...ss]) =>
xs.length ? [xs .slice (0, s), ... chunks (xs .slice (s), [...ss, s])] : []
const data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
const sizes = [4, 3, 3, 3]
console .log (chunks (data, sizes))
.as-console-wrapper { max-height: 100% !important; top: 0; }
通过将[s, ...ss]
替换为[...ss, s]
,我们传递一个大小数组的循环版本,例如,[4, 3, 3, 3]
变为[3, 3, 3, 4]
。这使得一步一步的解析变得很容易。
https://stackoverflow.com/questions/60231799
复制相似问题