I have two arrays all with unique values and I want to compare them so that I get a list of all the values that consecutive
const array1 = [1a,4a,3h,78h,5b,6b,7h]
const array2 = [3h,1a,4a,5b,6b,7h]
In this case I want to compare any number of consecutively matching values I want a list of all the pairs or any number of consecutively matching unique values they have which then gives me a list like this
const array3 =[[1a,4a],[5b,6b,7h]]
what would be the best way to go about this?
fetchValues = (array1, array2) => {
let result = [[]];
let loop = (i, j) => {
if (i >= array1.length || j >= array2.length) {
return;
}
if (array1[i] == array2[j]) {
result[result.length - 1].push(array1[i]);
loop(++i, ++j);
return;
}
let nextIndex1 = array1.indexOf(array2[j], i);
let nextIndex2 = array2.indexOf(array1[i], j);
nextIndex1 = nextIndex1 < 0 ? Infinity : nextIndex1;
nextIndex2 = nextIndex2 < 0 ? Infinity : nextIndex2;
if (nextIndex1 !== Infinity || nextIndex2 !== Infinity) {
result[result.length - 1].length === 0 || result.push([]);
nextIndex1 > nextIndex2 ? loop(i, nextIndex2) : loop(nextIndex1, j)
}
}
loop(0, 0);
const finalresult= result.filter(array=>array.length>1)
return finalresult;
}
This is the way I got it work for me if any one has another way then please feel free to share