Skip to content

Instantly share code, notes, and snippets.

@baybatu
Last active March 11, 2021 03:47
Show Gist options
  • Save baybatu/5663f238534290d15be7 to your computer and use it in GitHub Desktop.
Save baybatu/5663f238534290d15be7 to your computer and use it in GitHub Desktop.
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