/** * 把有序数字数组按连续分组 * [0,1,2,5,6,9] => [ * [0,1,2], * [5,6], * [9] * ] * @param numbers 数字数组 * @param onlyRange 是否只返回范围([[0,1,2,3]] => [[0,3]]) */ export function groupNumber(numbers: number[], onlyRange?: boolean): number[][] { let result = numbers.reduce((r: any, n) => { const lastSubArray = r[r.length - 1] if (!lastSubArray || lastSubArray[lastSubArray.length - 1] !== n - 1) { r.push([]) } r[r.length - 1].push(n) return r }, []) if (onlyRange) { result = result.map((x: any) => [x[0], x[x.length - 1]]) } return result }