Given a sorted array of ints for example
a = [0,1,2,5,6,9];
I would like to identify the ranges like
[
[0,1,2],
[5,6],
[9]
]
So far I have tried a double/triple loop but it nests to really nasty code. Maybe this problem can be solved using recursion or other smart tricks?
input
b = [0,1,5,6,7,9];
output
[
[0,1],
[5,6,7],
[9]
]
Iterate with Array#reduce
, and whenever the last number is not equal to the new number - 1, add another sub array. Add the current number to the last sub array:
const a = [0,1,2,5,6,9];
const result = a.reduce((r, 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;
}, []);
console.log(result);
Array.reduce like @OriDrori has done works well.
Another idea is just using a simple for loop, and slice.
function groupArray(a) {
const ret = [];
if (!a.length) return ret;
let ixf = 0;
for (let ixc = 1; ixc < a.length; ixc += 1) {
if (a[ixc] !== a[ixc-1] + 1) {
ret.push(a.slice(ixf, ixc));
ixf = ixc;
}
}
ret.push(a.slice(ixf, a.length));
return ret;
}
console.log(JSON.stringify(groupArray([0,1,2,5,6,9])));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With