2 回答
TA贡献2037条经验 获得超6个赞
您可能会考虑创建数组的副本(以避免改变原始数组),然后拼接项目直到它为空,检查并切换指示是否在当前迭代中删除 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);
TA贡献1796条经验 获得超4个赞
您可以创建一个接受数组和块大小数组的函数。该函数迭代数组,在块大小之间循环,并使用 slice 从原始数组中获取当前块大小:
const chunks = (arr, chunkSize) => {
const result = [];
let current = -1;
for (let i = 0; i < arr.length; i += chunkSize[current]) {
current = (current + 1) % chunkSize.length;
result.push(arr.slice(i, i + chunkSize[current]));
}
return result;
}
const dataset = [{"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 result = chunks(dataset, [6, 3]);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
添加回答
举报