Last active
December 14, 2024 12:42
-
-
Save youyoumu/8e74f8c7993dbb5194e326ed882c6111 to your computer and use it in GitHub Desktop.
Utility function to segment array into array of array with defined length
This file contains hidden or 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
/** Segment array into array of array with defined length | |
* @example const data = [ | |
* {name: "A"}, | |
* {name: "B"}, | |
* {name: "C"} | |
* ]; | |
* | |
* const segmented = segmentArray(data, 2); | |
* console.log(segmented); // [[{name: "A"}, {name: "B"}], [{name: "C"}]] | |
*/ | |
export function segmentArray<T>(arr: T[], segmentLength: number): T[][] { | |
return arr.reduce((result: T[][], item: T, index: number) => { | |
const segmentIndex = Math.floor(index / segmentLength); | |
if (!result[segmentIndex]) { | |
result[segmentIndex] = []; | |
} | |
result[segmentIndex].push(item); | |
return result; | |
}, []); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment