I want to split an array into n subarrays. I don't care how many elements end up in each array but the elements must be spread through all the available sub arrays.
Like this, solutions A & B are two ways of doing it but I'm looking for Solution A:
a = [1,2,3,4,5,6,7,8,9]
into_subarrays(a, 2);
- Solution A => [[1,3,5,7,9],[2,4,6,8]]
- Solution B => [[1,2,3,4,5],[6,7,8,9]]
into_subarrays(a, 4);
- Solution A => [[1,5,9],[2,6],[3,7],[4,8]]
- Solution B => [[1,2,3],[4,5],[6,7],[8,9]]
into_subarrays(a, 6);
- Solution A => [[1,7],[2,8],[3,9],[4],[5],[6]]
- Solution B => [[1,2],[3,4],[5,6],[7],[8],[9]]
into_subarrays(a, 12);
- Solution A => [[1],[2],[3],[4],[5],[6],[7],[8],[9],[],[],[]]
- Solution B => [[1],[2],[3],[4],[5],[6],[7],[8],[9],[],[],[]]
I have this solution, I just want to make sure it's as efficient as possible:
into_subarrays(myArray, chunks=2){
var a = myArray.slice(); //Copy array so that the original is not modified
var i = 0;
var result = [];
while(a.length){
//Create array if needed
if (typeof result[i] == 'undefined'){
result[i] = [];
}
result[i].push(a.shift());
i++;
i = (i == chunks) ? 0 : i; //Wrap around chunk selector
}
return result;
}
Thanks.
