Created
April 4, 2021 01:07
-
-
Save RodrigoNovais/b93e5b7b5574aee799c7d3a62a60dba3 to your computer and use it in GitHub Desktop.
Create an array of elements split into groups the length of size
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
/** | |
* 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