我正在尝试将一组对象拆分为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 = [];
}
}
所以数据最终看起来像这样:
答案 0 :(得分:2)
第一个数组有两个项目,因为i === 1
1%3
会导致1
从计数器1
开始可能是一个解决方案
data = [1,2,3,4,5,6,7]
var newData = [];
// var setOfThree = []; // not required
var j = 0
newData.push([]);
//pushing at the very begining, this way we won't miss if the data
// is not in groups of 3
for (i = 1; i <= data.length; i++) {
// always updating the final array
newData[j].push(data[i-1]);
if (i % 3 == 0) {
newData.push([]);
j++;
}
}
if (newData[0].length === 0) {
// if the data you received was epmty
newData.pop()
}
console.log(newData)
答案 1 :(得分:0)
这是一个递归实现,带有一些es6糖
var input = [1,2,3,4,5,6,7,8]
function groupByThree([a,b,c,...rest]){
if (rest.length === 0) return [[a,b,c].filter(x => x!==undefined)]
return [[a,b,c]].concat(groupByThree(rest))
}
console.log(groupByThree(input))
答案 2 :(得分:0)
这是一个非常干净和有效的解决方案:
let groupByN = (n, data) => {
let result = [];
for (i = 0; i < data.length; i += n) result.push(data.slice(i, i + n));
return result;
};
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 ])));