Skip to content

Instantly share code, notes, and snippets.

@nikvdp
Created January 20, 2016 20:03
Show Gist options
  • Save nikvdp/6037387dbd7a853b10c4 to your computer and use it in GitHub Desktop.
Save nikvdp/6037387dbd7a853b10c4 to your computer and use it in GitHub Desktop.
Split's an array into array's of n length
/**
*
* Split the array into arrays of n each,
* e.g. if n is 2 [1,2,3,4,5,6] becomes [[1,2], [3,4], [5,6]
*
* @param inputArr - Array
* @param n - Number
*/
function splitBy(inputArr, n) {
var result = [];
var innerArr = [];
inputArr.forEach(function(item, idx) {
innerArr.push(item);
if (idx === 0) {
return;
}
if ((idx+1) % n === 0) {
result.push(innerArr);
innerArr = [];
}
});
if (innerArr.length > 0) {
result.push(innerArr);
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment