Construct an 2D array of contiguous elements comparing master and incident arrays Requirement:

Based on mainArray which contains the master list of items, and compArray which has items of interest; construct a 2 dimensional third array that contains the array of contiguous elements.

The purpose of this requirement is for plotting poly-line on map wherever an incident occurred in contiguous manner, plotted using the finalArray of locations.

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];

// produces finalArray
[[ 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;
let finalArray = [];
let currentArray = null;

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

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

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

console.log(mainArray);
console.log(compArray);
console.log('finl arr:');
for (let i = 0; i &lt; finalArray.length; i++) {
  const e = finalArray[i];
  console.log(e);
}
The code could be reduced to a single line by utilizing Array.prototype.reduce()



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];

const finalArray = mainArray.reduce((a, b) =&gt; {
  // `c` is boolean result of checking if `compArray` includes `b`
  // `x` is first, and if matching elements found, last array in `finalResult`
  const [c, x] = [compArray.includes(b), a[a.length - 1]];
  // if `c` push `b` to last array of `a`
  if (c) x.push(b)
  // else if `x.length` push a new array to `a`
  else if (x.length) a.push([]);
  // return `a`
  return a;
}, [[]]); // pass initial array containing single array `a` to `reduce`

console.log(finalArray);