2 回答

TA貢獻2037條經(jīng)驗 獲得超6個贊
您可能會考慮創(chuàng)建數(shù)組的副本(以避免改變原始數(shù)組),然后拼接項目直到它為空,檢查并切換指示是否在當前迭代中刪除 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條經(jīng)驗 獲得超4個贊
您可以創(chuàng)建一個接受數(shù)組和塊大小數(shù)組的函數(shù)。該函數(shù)迭代數(shù)組,在塊大小之間循環(huán),并使用 slice 從原始數(shù)組中獲取當前塊大?。?/p>
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; }
添加回答
舉報