Skip to content

Instantly share code, notes, and snippets.

@JarrodMFlesch
Last active May 11, 2024 11:34
Show Gist options
  • Save JarrodMFlesch/6c880aeb0dd767474dc39f0c08cca454 to your computer and use it in GitHub Desktop.
Save JarrodMFlesch/6c880aeb0dd767474dc39f0c08cca454 to your computer and use it in GitHub Desktop.
Segment Array
function segmentArray<T>(arrayToSegment: T[], segmentSize: number): T[][] {
const segmentedArray = arrayToSegment.reduce(
(segments, item) => {
const newSegments: any[] = [...segments]
if (newSegments[newSegments.length - 1].length === segmentSize) {
newSegments[newSegments.length] = [item]
} else {
newSegments[newSegments.length - 1].push(item)
}
return newSegments
},
[[]],
)
return segmentedArray
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment