在javascript中将数组拆分为3个组[重复]

问题描述 投票:0回答:3

这个问题在这里已有答案:

我试图将一组对象分成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

javascript arrays
3个回答
2
投票

第一个数组得到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)

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))

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 ])));
© www.soinside.com 2019 - 2024. All rights reserved.