将一个数组分组以根据索引形成三个数组 [英] Group an array to form three arrays based on the index

查看:51
本文介绍了将一个数组分组以根据索引形成三个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对数组进行排序,使其返回三个数组.所以

I want to sort an array in a way that it gives back three arrays. So

var myArray = ['1','2','3','1','2','3','1','2','3','1','2','3','1','2','3','1','2','3','1','2','3','1','2','3','1','2','3','1','2','3','1','2','3','1','2','3','1','2','3','1','2','3','1','2','3','1','2','3','1','2','3','1','2','3'];

此处的值可以是数字,字符串,对象等.

here the values can be numbers, string, objects etc.

我想要三个数组,例如:

I want three arrays Like :

var myArray1 = ['1','1','1','1','1','1','1','1','1','1'];
var myArray2 = ['2','2','2','2','2','2','2','2','2','2'];
var myArray3 = ['3','3','3','3','3','3','3','3','3','3'];

推荐答案

您可以创建一个通用函数,该函数将根据提供的 n 对数组进行分组.根据 index%n 的结果,将它们推入特定的数组.在这里, n = 3 .如果您使用 i%2 ,这将根据奇数和偶数索引将数字分布到2个数组中.

You could create a generic function which will group the array based on the n provided. Based on the result of index % n, push them into specific arrays. Here, n = 3. If you use i % 2, this will distribute the numbers into 2 arrays based on odd and even indices.

const myArray = ['1', '2', '3', '1', '2', '3', '1', '2', '3', '1', '2', '3', '1', '2', '3', '1', '2', '3', '1', '2', '3', '1', '2', '3', '1', '2', '3', '1', '2', '3', '1', '2', '3', '1', '2', '3', '1', '2', '3', '1', '2', '3', '1', '2', '3', '1', '2', '3', '1', '2', '3', '1', '2', '3'];

function group(array, n) {
  return myArray.reduce((acc, number, i) => {
    acc[i % n] = acc[i % n] || [];
    acc[i % n].push(number);
    return acc;
  }, [])
}

const grouped = group(myArray, 3);

console.log(JSON.stringify(grouped[0]))
console.log(JSON.stringify(grouped[1]))
console.log(JSON.stringify(grouped[2]))

这篇关于将一个数组分组以根据索引形成三个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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