Skip to content

Instantly share code, notes, and snippets.

@misterussell
Created November 15, 2016 16:09
Show Gist options
  • Save misterussell/90405b13448ba7f671700e584ed09f6f to your computer and use it in GitHub Desktop.
Save misterussell/90405b13448ba7f671700e584ed09f6f to your computer and use it in GitHub Desktop.
Splits an array into subarrays of a specified length.
function subArray(array, length) {
// get an array
// for each over the array
// if the index is length spots in
// the numbers it traversed should be kept in an
// new array
let storage = [];
let i = 0;
//
while (storage.length < (array.length / length)) {
// takes length amount of numbers from the original and push them into
// smaller array which is then pushed into storage
let subArr = array.slice(i, i + length);
storage.push(subArr);
console.log(storage);
i += length;
}
return storage;
}
subArray([1,2,3,4,5,6], 2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment