I have a Select Option List where I have fruit in a random order, some with a "Out Of Stock" label on them. What i want to do is sort them all by alphabetical order then move the "Out Of Stock" label from the start of the flavour to the end of the flavour so they would display as: "Lemon - Out Of Stock" instead of how it currently is: "Out Of Stock - Lemon". So far I have the following where I'm looking for the "Out Of Stock" label and then adding it to the end, but not sure how I would go about removing it from the start or if there is a better way to achieve what i'm looking to do.
document.querySelectorAll('.form-dropdown').forEach(function(select) {
Array.from(select.options).forEach(function(option) {
if (option.innerText.includes("Out of stock")) {
select.insertBefore(option, select.options[1]);
option.innerText += (' - Out of stock');
}
});
var cl = document.querySelector('.form-dropdown');
var clTexts = new Array();
for (i = 1; i < cl.length; i++) {
clTexts[i - 1] =
cl.options[i].text.toUpperCase() + "," +
cl.options[i].text + "," +
cl.options[i].value;
}
clTexts.sort();
for (i = 1; i < cl.length; i++) {
var parts = clTexts[i - 1].split(',');
cl.options[i].text = parts[1];
cl.options[i].value = parts[2];
}
});
<select class="form-dropdown">
<option disabled="" value="">Choose option</option>
<option value="6">Watermelon</option>
<option value="2">Out of stock - Cherry</option>
<option value="3">Kiwi</option>
<option value="0">Apple</option>
<option value="4">Out of stock - Lemon</option>
<option value="1">Banana</option>
<option value="5">Out of stock - Melon </option>
<option value="4">Out of stock - Pineapple</option>
<option value="1">Strawberry</option>
<option value="5">Out of stock - Khaki</option>
</select>