Last active
May 11, 2024 11:34
-
-
Save JarrodMFlesch/6c880aeb0dd767474dc39f0c08cca454 to your computer and use it in GitHub Desktop.
Segment Array
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
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