Skip to content

Instantly share code, notes, and snippets.

@ulpian
Created January 14, 2022 18:54
Show Gist options
  • Select an option

  • Save ulpian/6d49546409cb12c29860c1d3624dc94c to your computer and use it in GitHub Desktop.

Select an option

Save ulpian/6d49546409cb12c29860c1d3624dc94c to your computer and use it in GitHub Desktop.
groupArrayElements in typescript
// 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
@ulpian
Copy link
Author

ulpian commented Jan 14, 2022

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment