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\'
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]))