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>
Spectric
  • 30,714
  • 6
  • 20
  • 43
CJ Velasco
  • 53
  • 3
  • Does this answer your question? [Get all unique values in a JavaScript array (remove duplicates)](https://stackoverflow.com/questions/1960473/get-all-unique-values-in-a-javascript-array-remove-duplicates) – dale landry May 23 '21 at 05:11

2 Answers2

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>
Mamun
  • 66,969
  • 9
  • 47
  • 59
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>
Spectric
  • 30,714
  • 6
  • 20
  • 43