Created
January 14, 2022 18:54
-
-
Save ulpian/6d49546409cb12c29860c1d3624dc94c to your computer and use it in GitHub Desktop.
groupArrayElements in typescript
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
| // groupArrayElements([1, 2, 3, 4, 5], 3); | |
| const groupArrayElements = ( | |
| array: Array<number>, | |
| length: number | |
| ): Array<Array<number>> => { | |
| const ar: Array<any> = []; | |
| for (let x of array) { | |
| const prevLength: number = ar[x - 2] ? ar[x - 2].length : 0; | |
| const s: number = prevLength !== 0 ? (prevLength * x) - length : 0; | |
| const e: number = array[s] + (length - 1); | |
| ar[x - 1] = array.slice(s, e); | |
| if (array.length <= e) break; | |
| } | |
| return ar; | |
| } | |
| const groupedElements = groupArrayElements([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3); | |
| console.log(groupedElements); | |
| // npm i ts-node | |
| // npx ts-node groupArrayBy.ts |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a function written to group a sequence of numbers into a group of array of sequences depending on the length that each array should be. This was rapidly written and with a purpose of being easily read by another dev.