gpt4 book ai didi

javascript - 在javascript中将数组分成3组

转载 作者:行者123 更新时间:2023-12-01 01:59:19 26 4
gpt4 key购买 nike

我正在尝试将一个对象数组拆分为 3 个对象组,但出现了一个小问题。我运行代码,它将第一组分成 2 组,其余组分成 3 组。我希望最后一组包含剩余的元素。因此,例如,如果有 21 个对象,那么最后一组应该有 2 个对象,但第一组是有 2 个对象的组。如何使最后一组成为包含其余对象的组?

var newData = [];
var setOfThree = [];

for (i = 0; i < data.length; i++) {
setOfThree.push(data[i]);

if (i % 3 == 1) {
newData.push(setOfThree);
setOfThree = [];
}
}

所以数据最终看起来像这样:

enter image description here

最佳答案

这是一个非常干净且高效的解决方案(利用 Array.prototype.slice 自动 chop 结果的事实):

let groupByN = (n, arr) => {
let result = [];
for (let i = 0; i < arr.length; i += n) result.push(arr.slice(i, i + n));
return result;
};

console.log(JSON.stringify(groupByN(3, [])));
console.log(JSON.stringify(groupByN(3, [ 1 ])));
console.log(JSON.stringify(groupByN(3, [ 1, 2 ])));
console.log(JSON.stringify(groupByN(3, [ 1, 2, 3 ])));
console.log(JSON.stringify(groupByN(3, [ 1, 2, 3, 4 ])));
console.log(JSON.stringify(groupByN(3, [ 1, 2, 3, 4, 5 ])));
console.log(JSON.stringify(groupByN(3, [ 1, 2, 3, 4, 5, 6 ])));
console.log(JSON.stringify(groupByN(3, [ 1, 2, 3, 4, 5, 6, 7 ])));
console.log(JSON.stringify(groupByN(3, [ 1, 2, 3, 4, 5, 6, 7, 8 ])));

关于javascript - 在javascript中将数组分成3组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50748099/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com