我到底如何将一个数组分成 6 个 block ,然后是 3 个 block ,然后是 6 个 block ,然后是 3 个 block ,依此类推?
假设我有这个数据集:
const datasaet = [
{ text: 'hi1' },
{ text: 'hi2' },
{ text: 'hi3' },
{ text: 'hi4' },
{ text: 'hi5' },
{ text: 'hi6' },
{ text: 'hi7' },
{ text: 'hi8' },
{ text: 'hi9' },
{ text: 'hi10' },
{ text: 'hi11' },
{ text: 'hi12' },
{ text: 'hi13' },
{ text: 'hi14' },
{ text: 'hi15' },
{ text: 'hi16' },
]
我需要将它分成一个数组,如下所示:
const expected = [
[
{ text: 'hi1' },
{ text: 'hi2' },
{ text: 'hi3' },
{ text: 'hi4' },
{ text: 'hi5' },
{ text: 'hi6' },
],
[
{ text: 'hi7' },
{ text: 'hi8' },
{ text: 'hi9' },
],
[
{ text: 'hi10' },
{ text: 'hi11' },
{ text: 'hi12' },
{ text: 'hi13' },
{ text: 'hi14' },
{ text: 'hi15' },
{ text: 'hi16' },
]
]
本质上,我正在做的是将数组分成 6 个 block (如果是事件)和 3 个 block (如果是奇数)。
但是我不知道该怎么做。我当前的尝试看起来像这样,我可以将它完美地分成 6 block ,但是我该如何去做接下来的 3 block ,然后是接下来的 6 block ,依此类推:
const grouped = datasaet.reduce(
(initital: any[], current, index, items) => {
const isFirstOfSix = index % 6 === 0
if (isFirstOfSix) {
const nextSix = items.slice(index, index + 6)
initital.push(nextSix)
}
return initital
},
[]
)
最佳答案
您可能会考虑创建数组的副本(以避免改变原始数组),然后拼接项目直到其为空,检查并切换一个 bool 值以指示是否在当前迭代中删除 6 个或 3 个项目:
const datasaet = [
{ text: 'hi1' },
{ text: 'hi2' },
{ text: 'hi3' },
{ text: 'hi4' },
{ text: 'hi5' },
{ text: 'hi6' },
{ text: 'hi7' },
{ text: 'hi8' },
{ text: 'hi9' },
{ text: 'hi10' },
{ text: 'hi11' },
{ text: 'hi12' },
{ text: 'hi13' },
{ text: 'hi14' },
{ text: 'hi15' },
{ text: 'hi16' },
]
const tempArr = datasaet.slice();
const output = [];
let removeSix = true;
while (tempArr.length) {
output.push(tempArr.splice(0, removeSix ? 6 : 3));
removeSix = !removeSix;
}
console.log(output);
关于javascript - JS 将数组拆分为 X 个 block ,然后是 Y 个 block ,依此类推,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58353793/