Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sort two array at the same time based on each other

I have two arrays sorted and ready like this:

const mains = [1, 5, 6, 8 , 12];
const secondaries = [1, 6, 12];

I want to create a div with multiple spans dynamically based on above arrays like theses:

<span class="main">${unit}</span>

<span class="secondary">${unit}</span>

The issue is I’m unable to find a proper solution to sort both arrays and create those spans .

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

In the given arrays the result should be this:

<span class="main"> 1 </span>

<span class="secondary"> 1 </span>

<span class="main"> 5 </span>

<span class="main"> 6 </span>

<span class="secondary"> 6 </span>

<span class="main"> 8 </span>

<span class="main"> 12 </span>

<span class="secondary"> 12 </span>

>Solution :

The following completes the task in O(n) time.

const mains = [1, 5, 6, 8 , 12];
const secondaries = [1, 6, 12];

const min = Math.min(Math.min(...mains),Math.min(...secondaries));
const max = Math.max(Math.max(...mains),Math.max(...secondaries)); 

for (let i=min; i<=max; i++){
  if (mains.includes(i)) console.log(`<span class="main">${i}</span>`);
  if (secondaries.includes(i)) console.log(`<span class="secondaries">${i}</span>`);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading