Last active
March 11, 2021 03:47
-
-
Save baybatu/5663f238534290d15be7 to your computer and use it in GitHub Desktop.
Splitting array into list of subarrays in javascript
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
/* | |
* Splits array into subarrays. | |
* count parameter indicates that how many item per subarray contains. | |
* Example usage: splitIntoSubArray([1,2,3,4,5], 2) -> [[1, 2], [3, 4], [5]] | |
*/ | |
function splitIntoSubArray(arr, count) { | |
var newArray = []; | |
while (arr.length > 0) { | |
newArray.push(arr.splice(0, count)); | |
} | |
return newArray; | |
} |
Nice, but splice mutate array
Yes it has side effect. You may want to see different approaches on this problem: https://gist.github.com/webinista/11240585
Hi @Andrew-Dyachenko,
what about this -
sp_array = [1,2,3,4,5,6,7,8,9,10]
let pivot = _.ceil(sp_array.length / 4);
array_chunk = _.chunk(sp_array, pivot);
Hi @Andrew-Dyachenko,
what about this -sp_array = [1,2,3,4,5,6,7,8,9,10] let pivot = _.ceil(sp_array.length / 4); array_chunk = _.chunk(sp_array, pivot);
Thanks, but it seems that it needs underscore.js
dependency.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you!