Skip to content

Instantly share code, notes, and snippets.

@yano3nora
Last active June 11, 2023 10:14
Show Gist options
  • Save yano3nora/e3bd3bf3f5b1cc471b24496190f70e29 to your computer and use it in GitHub Desktop.
Save yano3nora/e3bd3bf3f5b1cc471b24496190f70e29 to your computer and use it in GitHub Desktop.
[js: Chunk Array] Split array elements by chunk number. #js
/**
* @example chunk([1, 2, 3, 4, 5, 6, 7], 3) // [[1, 2, 3], [4, 5, 6], [7]]
* @link https://qiita.com/yarnaimo/items/e92600237d65876f8dd8
*/
export const chunk = <T>(arr: T[], size: number) => (
arr.reduce((newarr, _, i) => (
i % size ? newarr : [...newarr, arr.slice(i, i + size)]
), [] as T[][])
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment