Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Splitting array into list of subarrays in javascript
/*
* 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;
}
@drew-codes
Copy link

Thank you!

@Andrew-Dyachenko
Copy link

Nice, but splice mutate array

@baybatu
Copy link
Author

baybatu commented Oct 16, 2018

Hi @Andrew-Dyachenko,

Yes it has side effect. You may want to see different approaches on this problem: https://gist.github.com/webinista/11240585

@memon07
Copy link

memon07 commented Mar 30, 2019

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);

@baybatu
Copy link
Author

baybatu commented Mar 30, 2019

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