Skip to content

Instantly share code, notes, and snippets.

@youyoumu
Last active December 14, 2024 12:42
Show Gist options
  • Save youyoumu/8e74f8c7993dbb5194e326ed882c6111 to your computer and use it in GitHub Desktop.
Save youyoumu/8e74f8c7993dbb5194e326ed882c6111 to your computer and use it in GitHub Desktop.
Utility function to segment array into array of array with defined length
/** 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