Created
January 20, 2016 20:03
-
-
Save nikvdp/6037387dbd7a853b10c4 to your computer and use it in GitHub Desktop.
Split's an array into array's of n length
This file contains hidden or 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
/** | |
* | |
* 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