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

This comment has been minimized.

Copy link

commented Sep 12, 2018

Thank you!

@Andrew-Dyachenko

This comment has been minimized.

Copy link

commented Oct 15, 2018

Nice, but splice mutate array

@baybatu

This comment has been minimized.

Copy link
Owner Author

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

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link
Owner Author

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
You can’t perform that action at this time.