javascript – Constructs a 2D array of contiguous elements comparing master and incident arrays

Requirement:

Based on mainArray which contains the master list of articles, and compArray who has objects of interest; construct a third 2-dimensional array containing the array of contiguous elements.

The purpose of this requirement is to draw the polyline on the map whenever an incident occurs contiguously, traced with the help of the final table places.

Example:

const mainArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
const compArray = [1, 2, 3, 6, 7, 11, 12, 13, 15];

// finalArray product
[[ 1, 2, 3 ],[ 6, 7 ],[ 11, 12, 13 ],[ 15 ]]

My current solution:

console.clear ();

const mainArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
const compArray = [1, 2, 3, 6, 7, 11, 12, 13, 15];
let compArrayIndex = 0;
leave finalArray = [];
let currentArray = null;

for (let i = 0; i <mainArray.length; i ++) {
const e = mainArray[i];

if (e === compArray[compArrayIndex]) {
if (! currentArray) {
currentArray = [];
}
currentArray.push (e);
compArrayIndex ++;
} other {
if (currentArray) {
finalArray.push ([...currentArray])
currentArray = null;
}
}
}

if (currentArray) {
finalArray.push ([...currentArray])
currentArray = null;
}

console.log (mainArray);
console.log (compArray);
console.log (& # 39; finl arr: & # 39;);
for (let i = 0; i <finalArray.length; i ++) {
const e = finalArray[i];
console.log (e);
}