Although this code works fine, it feels wrong. There must be a more elegant way to use JavaScript here. How I improve it?
Both el and fchoices are collections of <option> for a <choice> element. The goal is to take the <option> elements from el and append them to fchoices's parent only if they don't already exist there. fieldChoices is the parent of the fchoices <option> elements.
var values = [];
for (let i = 0; i < fchoices.length; i++) {
values.push(fchoices[i].value);
}
var offset = 0;
var ellength = el.length;
for (let i = 0; i < ellength; i++) {
if (values.includes(el[i - offset].value)){
el.remove(i-offset);
offset++;
}
}
var fieldChoices = document.getElementById("id_field")
fieldChoices.style.scrollBehavior = "smooth";
for (let i = 0; i < el.length; i++) {
el[i].selected = true;
fieldChoices.appendChild(el[i]);
setTimeout(function() {fieldChoices.scrollTop = fieldChoices.scrollHeight;}, 50);
}
After that I am also making them selected and scroll down so they are visible.