This function returns an array of arrays, each of which contains a series of consecutive numbers from the original array.
JavaScript:
let consecutiveArrays = arr => arr.reduce((result, num, i) => { if (num !== arr[i-1] + 1) result.push([]); result[result.length - 1].push(num); return result; }, [[]]);
// Example
console.log(consecutiveArrays([1, 2, 3, 5, 6, 8])); // [[1, 2, 3], [5, 6], [8]]
console.log(consecutiveArrays([10, 11, 12, 14, 15, 16, 18])); // [[10, 11, 12], [14, 15, 16], [18]]
TypeScript:
let consecutiveArrays = (arr: number[]): number[][] => arr.reduce((result: number[][], num: number, i: number) => { if (num !== arr[i-1] + 1) result.push([]); result[result.length - 1].push(num); return result; }, [[]]);
// Example
console.log(consecutiveArrays([1, 2, 3, 5, 6, 8])); // [[1, 2, 3], [5, 6], [8]]
console.log(consecutiveArrays([10, 11, 12, 14, 15, 16, 18])); // [[10, 11, 12], [14, 15, 16], [18]]