【问题标题】:Splitting array into groups of 3 in javascript [duplicate]在javascript中将数组分成3组[重复]
【发布时间】:2018-11-17 18:35:13
【问题描述】:

我正在尝试将一组对象拆分为 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 = [];
  }
}

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

【问题讨论】:

  • 1%n === 1 ???

标签: javascript arrays


【解决方案1】:

这是一个非常干净有效的解决方案:

let groupByN = (n, data) => {
  let result = [];
  for (let 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 ])));

【讨论】:

  • 美丽。对于那些可能对语法有疑问的人,您可能需要添加“让”:for (let i = 0; i &lt; data.length; i += n)...
  • 好收获@HigoChumbo!我已经编辑了
【解决方案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)

【讨论】:

    【解决方案3】:

    这里是递归实现,带有一些 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))

    【讨论】:

      猜你喜欢
      • 2015-02-25
      • 1970-01-01
      • 2020-05-20
      • 2013-07-15
      • 2017-09-10
      • 1970-01-01
      • 2016-07-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多