将一个数组分组以根据索引形成三个数组
问题描述:
我想对数组进行排序,使其返回三个数组.所以
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]))