Skip to content

Instantly share code, notes, and snippets.

@RodrigoNovais
Created April 4, 2021 01:07
Show Gist options
  • Save RodrigoNovais/b93e5b7b5574aee799c7d3a62a60dba3 to your computer and use it in GitHub Desktop.
Save RodrigoNovais/b93e5b7b5574aee799c7d3a62a60dba3 to your computer and use it in GitHub Desktop.
Create an array of elements split into groups the length of size
/**
* Creates an array of elements split into groups the length of size
*
* @template T
* @param {T[]} input
* @param {number} size
* @returns {T[][]}
*/
export const chunk = <T>(input: T[], size: number): T[][] => {
return input.reduce((array, item, index) => {
return index % size === 0
? [...array, [item]]
: [...array.slice(0, -1), [...array.slice(-1)[0], item]];
}, [] as T[][]);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment