I have array structured like this:
[
[8,[1]],
[15,[2]],
[20,[3]],
[23,[4,41]],
[497,[18]],
[1335,[38]],
[2092,[39,55,61]],
[3615,[5]],
[4121,[14]],
[5706,[39,55,61]],
[5711,[62]],
[5714,[63]],
[5719,[64]],
[6364,[38]]
]
I use the modified code from this answer to find consecutive numbers but I can't adapt it to also find consecutive numbers from arrays with multiple values
This is my code :
const a = [
[8,[1]],
[15,[2]],
[20,[3]],
[23,[4,41]],
[497,[18]],
[1335,[38]],
[2092,[39,55,61]],
[3615,[5]],
[4121,[14]],
[5706,[39,55,61]],
[5711,[62]],
[5714,[63]],
[5719,[64]],
[6364,[38]]
];
// this variable will contain arrays
let finalArray = [];
// Create a recursive function
function checkPrevNextNumRec(array) {
let tempArr = [];
// if the array contaon only 1 element then push it in finalArray and
// return it
if (array.length === 1) {
finalArray.push(array);
return
}
// otherside check the difference between current & previous number
for (let i = 1; i < array.length; i++) {
if (array[i][1][0] - array[i - 1][1][0] === 1) {
// if current & previous number is 1,0 respectively
// then 0 will be pushed
tempArr.push(array[i - 1]);
} else {
// if current & previous number is 5,2 respectively
// then 2 will be pushed
tempArr.push(array[i - 1])
// create a an array and recall the same function
// example from [0, 1, 2, 5, 6, 9] after removing 0,1,2 it
// will create a new array [5,6,9]
let newArr = array.splice(i);
finalArray.push(tempArr);
checkPrevNextNumRec(newArr)
}
// for last element if it is not consecutive of
// previous number
if (i === array.length - 1) {
tempArr.push(array[i]);
finalArray.push(tempArr)
}
}
}
checkPrevNextNumRec(a)
And here the result, as you can see, all the tables containing consecutive figures in [i][1][0]
have been grouped
[
[
[8,[1]],
[15,[2]],
[20,[3]],
[23,[4,41]]
],
[
[497,[18]]
],
[
[1335,[38]],
[2092, [39,55,61]]
],
[
[3615,[5]]
],
[
[4121,[14]]
],
[
[5706,[39,55,61]]
],
[
[5711,[62]],
[5714,[63]],
[5719,[64]]
],
[
[6364,[38]]
]
]
But I need that field 5706 is also included with 5711, 5714, and 5719, but obviously it is not included because is not in [i][1][0]
I thought of being inspired by this post but I cannot integrate it correctly
Can you help me?
Thanks!