15,905,614 members
See more:
How to divide this array:- [0, 1, 2, 3, 4, 5, 6, 7, 8, 12, 13, 14, 15] into two different arrays with one set of consecutive sequences in one array and another set of consecutive in another array.

for eg : array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 12, 13, 14, 15]

Desired output [0, 1, 2, 3, 4, 5, 6, 7, 8] and [12, 13, 14, 15]

The array should split into a number of consecutive sequences present in the array. If there are 3 consecutive sequences then the array should split into 3 different arrays with consecutive values and so on.

Another example = [1 ,2 ,3 ,4 5, 14, 15, 16, 22, 23, 24, 25]

Desired output [1, 2, 3, 4, 5] and [14, 15, 16] and [22, 23, 24, 25]

What I have tried:

```let arrnew = [0, 1, 2, 3, 4, 5, 6, 7, 8, 12, 13, 14, 15]
let arr2 = []

for (let j = 0; j < arrnew.length; j++) {
if (arrnew[j + 1] - 1 === arrnew[j]) {
arr2.push(arrnew[j])
}
}```

I tried this but this dint work. I am looking for a solution with inbuilt functions.
Posted
Updated 8-Jun-22 17:35pm

## Solution 1

Have a look at the splice function.

```let arrnew = [0, 1, 2, 3, 4, 5, 6, 7, 8, 12, 13, 14, 15, 17, 18, 20] ;
let arr2 = [];

for (let j = 0; j < arrnew.length-1; j++) {
if (arrnew[j + 1] - 1 !== arrnew[j]) {
arr2.push(arrnew.splice(0, j+1));
j = 0;
}
}

if (arrnew.length > 0) {
arr2.push(arrnew.splice(0));
}```