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>
Loop over the mains array, and check if there's a corresponding element in secondaries:
html = '';
mains.foreach(main => {
html += `<span class="main"> {$main} </span>`;
if (secondaries.includes(main) {
html += `<span class="secondary"> {$main} </span>`;
}
});
If the arrays are large, you should convert secondaries to a Set and use secondaries.has(main) instead of secondaries.includes(main).
const mains = [1, 5, 6, 8 , 12];
const secondaries = [1, 6, 12];
const min = Math.min(...mains, ...secondaries);
const max = Math.max(...mains, ...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>`);
}
You could merge them together, and as you merge them, create the span:
function span(val, class){
console.log(`<span class=${class}>${val}</span>`);
function mergeAndSpan(main, secondary){
let i = 0, j = 0;
while(i < main.length && j < secondary.length){
if(main[i] < secondary[j]){
span(main[i], 'main')
i++;
} else {
span(secondary[j], 'secondary')
j++;
}
}
while(i < main.length){
span(main[i], 'main')
i++;
}
while(j < secondary.length){
span(secondary[j], 'secondary')
j++;
}
}
mergeAndSpan(mains, secondaries);
This is effectively the merge portion of mergesort, modified slightly to create spans instead of putting the elements into an array. What it does is iterates through both, creating a span for the lower element, and incrementing its' variable. Then, once one of the arrays is empty, then it iterates through the other array and creates the span for each of its' elements.
And, because it is performing an operation on all of n elements, it takes O(n) time.