Get all arrays of consecutive elements

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]]
Member since January 2, 2019

As a seasoned WordPress developer with expertise in various tech stacks and languages, I bring years of experience to every project I handle. My passion for coding and dedication to delivering exceptional work ensures that each project I take on is of the highest quality. I specialize in creating custom themes, developing plugins, and building full-scale web systems. By staying up-to-date with the latest industry trends and best practices, I incorporate cutting-edge solutions into my work.

Comments

    Your email address will not be published. Required fields are marked *