Click here to Skip to main content
15,905,614 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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

1 solution

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));
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900