【发布时间】:2019-10-12 11:43:52
【问题描述】:
我怎样才能将一个数组分成 6 个块,然后是 3 个块,然后是 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 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 个块(如果是事件)和 3 个块(如果是奇数)。
但是我不知道该怎么做。我目前的尝试看起来是这样的,我可以将它完美地分成 6 块,但我该如何去做接下来的 3 块,然后是接下来的 6 块,依此类推:
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
},
[]
)
【问题讨论】:
标签: javascript arrays typescript grouping