Last active
October 11, 2016 08:21
-
-
Save lleaff/298f57f5a8eac7bbb75dda059aeb4631 to your computer and use it in GitHub Desktop.
arraySliceEveryN(array, n)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Slice an array every n elements. Don't leave out any elements from source array or | |
* empty spaces in the resulting slices. | |
* @example | |
* arraySliceEveryN([1,2,3,4,5,6,7], 3) | |
* //=> [[1,4,7],[2,5],[3,6]] | |
*/ | |
function arraySliceEveryN(array, n) { | |
let slices = Array(n); | |
const min_len = Math.floor(array.length / n); // Length without remaining elements | |
const rem = array.length - n * min_len; // Remaining elements | |
for (let m = 0; m < n; m++) { // Initialize slices | |
slices[m] = Array(min_len + (rem - m > 0 ? 1 : 0)); | |
} | |
for (let i = 0; i < array.length; i++) { | |
slices[i % n][Math.floor(i / n)] = array[i]; | |
} | |
return slices; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment