Skip to content

Instantly share code, notes, and snippets.

@lleaff
Last active October 11, 2016 08:21
Show Gist options
  • Save lleaff/298f57f5a8eac7bbb75dda059aeb4631 to your computer and use it in GitHub Desktop.
Save lleaff/298f57f5a8eac7bbb75dda059aeb4631 to your computer and use it in GitHub Desktop.
arraySliceEveryN(array, n)
/**
* 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