Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

107
Views
How to compare consecutive elements in two different arrays

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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

The only solution I can think of is (there should many better), first to create all the possible subarrays: eg: const array1 = [1a,4a,3h,78h,5b,6b,7h] const array2 = [3h,1a,4a,5b,6b,7h]

const subArray = [[1a,4a],[3h], [5b,6b,7h]]

once you have the subarray, you can map them to a new array with their Max location in either array with respect to subarray:

const maxLocation = [[1,2][2][4,5,6]]; Now you need to find the longest in sequence => [[1,2][4,5,6]]

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!