将数组元素分组为n个集合 [英] Group array elements into set of n

查看:64
本文介绍了将数组元素分组为n个集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组

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

我想将其分组为n个数组,以便result [0]中的前n个元素,result [1]中的前n个元素,如果有剩余元素,则将其丢弃.

I want to group it into a set of n arrays such that first n elements in result[0] next n elements in result[1] and if any element is remaining it is discarded.

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;
}

但是我无法获得预期的结果.我尝试了以下操作.

But I am unable to get expected result. I have tried following things.

  1. 地图功能
  2. 运行i循环到arr.len
  3. 检查 arr.len%7
  4. 为每个第三个元素创建一个数组.
  5. 此问题不是将数组拆分为块的重复,因为我必须丢弃多余的元素不能分为n组.
  6. 我必须保持原始数组不变,因为我在子组件的props上使用了它.我需要一个不会修改原始数组的函数.
  1. Map function
  2. Running i loop to arr.len
  3. Checking arr.len % 7
  4. Creating an array for every third element.
  5. This question is not duplicate of Split array into chunks because I have to discard extra elements that can not be grouped into sets of n.
  6. I have to keep the original array Immutable because I am using this on props in a child component. I need a function that does not modify the original array.

推荐答案

关于:

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;
}

这篇关于将数组元素分组为n个集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆