0

I have this drop-down menu. My goal is to transfer the elements of an array as choices on the drop-down menu. However, I want repeating array elements to be copied to the drop-down only once. I'm looking for transferring my array to another array without repetition. So, I can rather use that new array to transfer its element to the drop-down menu. For example, on the drop-down menu, the "kg" and "lbs" would only exist once instead of twice.

amountType = document.getElementById("amount-type");

arr = ["kg", "medium", "lbs", "liter", "kg", "small", "lbs"];

for (let i = 0; i < arr.length; i++) {
  let el = document.createElement("option");
  el.textContent = arr[i];
  el.value = arr[i];
  
  amountType.appendChild(el);
}
<select id="amount-type"></select>

1

2 Answers 2

2

First you can find the unique elements from the array using Set:

var amountType = document.getElementById("amount-type");

var arr = ["kg", "medium", "lbs", "liter", "kg", "small", "lbs"];
arr = [...new Set(arr)]; //get the unique elements
for (let i = 0; i < arr.length; i++) {
  let el = document.createElement("option");
  el.textContent = arr[i];
  el.value = arr[i];
  
  amountType.appendChild(el);
}
<select id="amount-type"></select>

Sign up to request clarification or add additional context in comments.

Comments

1

Try selecting the option with the current value. If an option exists with that value, the length of the array returned from querySelectorAll will be greater or equal to 1.

amountType = document.getElementById("amount-type");

arr = ["kg", "medium", "lbs", "liter", "kg", "small", "lbs"];
for (let i = 0; i < arr.length; i++) {
  if (amountType.querySelectorAll('option[value="' + arr[i] + "\"]").length == 0) {
    let el = document.createElement("option");
    el.textContent = arr[i];
    el.value = arr[i];
    amountType.appendChild(el);
  }
}
<select id="amount-type"></select>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.