将数组元素分组成n个集合

5

我有一个数组

let arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]; 

我希望将它分成一组n个数组,使得结果中的第一个n个元素在result [0]中,接下来的n个元素在result [1]中,如果有任何剩余的元素则被丢弃。

let sampleOutput = [[0, 1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12, 13]] for n = 7; 

这是我的代码:

function group5(arr, len) {
 let result = [];
 let loop=parseInt(arr.length/len)
 for (let i=0; i<arr.length; i+=len) {
  let x = []; let limitReached = false;
  for (let j=0; j<len; j++) {
   if (arr[i+j]) {
    x.push(arr[i+j]);
   } else {
    limitReached = true;
    break;
   }
  }
 if (!limitReached) {
  result.push(x);
 } else {
  break;
  }
 }
 return result;
}

但我无法得到预期的结果。我尝试了以下方法:
  1. 使用Map函数
  2. 运行i循环后检查arr.len
  3. 检查arr.len % 7
  4. 为每个第三个元素创建一个数组。
  5. 这个问题不是Split array into chunks重复的,因为我必须丢弃不能组成n个集合的额外元素。
  6. 我必须保持原始数组不可变,因为我在子组件中使用props。我需要一个不修改原始数组的函数。

3
可能是 Split array into chunks 的重复问题。 - Andreas
大家好,谢谢。我选择了以下解决方案。考虑此问题已关闭。 export function groupInChunks (arr, len) { let chunks = []; let i = 0; while((arr.length - i) >= len) { chunks.push(arr.slice(i, len + i)); i+=len; } return chunks; } - Vishu Bhardwaj
6个回答

4

使用Array.from非常简单。

const list = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14];

function chunkMaxLength(arr, chunkSize, maxLength) {
  return Array.from({length: maxLength}, () => arr.splice(0,chunkSize));
}

console.log(chunkMaxLength(list, 7, 2));


这就是为什么在重复问题的一个答案中提到了它。 - Andreas
是的,如果你仔细比较答案,你会发现它们之间的差异。@Andreas 这个答案与其他答案相反,它正在做OP所要求的,并且比其他答案中的Array.from方法更高效。 - baao

2

你觉得怎样:

function group5(arr, len) {
     let chunks = [];
     let copy   = arr.splice(); // Use a copy to not modifiy the original array
     while(copy.length > len) {
         chunks.push(copy.splice(0, len));
     }
     return chunks;
}

它不会丢弃无法分组为7个元素集合的额外元素。你的答案结果是[[0..6],[7..13],[14]],我不想要那些不能组成7个元素集合的元素。 - Vishu Bhardwaj
我更新了我的答案,现在返回了预期的结果。 - Grégory
嗨,这个解决方案非常正确。我该怎么做才能不修改原始数组呢?原始数组来自props(react-native),因此我不能修改它。 - Vishu Bhardwaj
我再次更新了我的答案,以便不修改原始数组。 :) - Grégory

2

我通常更喜欢声明性的解决方案(如mapreduce等),但在这种情况下,我认为for更易于理解:

function groupArray(array, num) {
  const group = [];

  for (let i = 0; i < array.length; i += num) {
    group.push(array.slice(i, i + num));
  }

  return group;
}

0

除了现有的方法之外,您还可以采用递归方法,如下所示

function chunks(a, size, r = [], i = 0) {
    let e = i + size;
    return e <= a.length ? chunks(a, size, [...r, a.slice(i, e)], e) : r;
}

function chunks(a, size, r = [], i = 0) {
    let e = i + size;
 return e <= a.length ? chunks(a, size, [...r, a.slice(i, e)], e) : r;
}

var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14];


console.log('Chunk with 3: ', chunks(arr, 3));
console.log('Chunk with 4: ', chunks(arr, 4));
console.log('Chunk with 5: ', chunks(arr, 5));
console.log('Chunk with 6: ', chunks(arr, 6));
console.log('Chunk with 7: ', chunks(arr, 7));


0
你可以使用reduce和filter的组合来实现预期的结果。这个例子给了你第三个控制长度的选项,使代码更具可重用性。

let arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]; 
const groupNumber = 7;
const groupCount = 2;


const groupArray = (group, size, length) => group.reduce((accumulator, current, index, original) =>   
  ((index % size) == 0)
    ? accumulator.concat([original.slice(index, index + size)])
    : accumulator, []
  ).filter((single, index) => index < length)

const test = groupArray(arr, groupNumber, groupCount);
console.log(test);

逐步操作

const groupArray = (group, size, length) => {
  // if (index modulus size) equals 0 then concat a group of 
  // length 'size' as a new entry to the accumulator array and 
  // return it, else return the accumulator
  const reducerFunc = (accumulator, current, index, original) =>   
  ((index % size) == 0)
    ? accumulator.concat([original.slice(index, index + size)])
    : accumulator

  // if the current index is greater than the supplied length filter it out
  const filterFunc = (single, index) => index < length;

  // reduce and filter original group
  const result = group.reduce(reducerFunc, []).filter(filterFunc)

  return result;
}

0

我能够用这段代码解决问题

function groupN(n, arr) {
  const res = [];
  let limit = 0;
  while (limit+n <= arr.length) {
    res.push(arr.slice(limit, n + limit));
    limit += n
  }
  return res
}

如果我们想将最后一组元素分组,但它们不属于n的组,则无法正常工作。 - Prinju Koshy Vaidyan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接