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 .
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>`);
}