user2592331
user2592331

Reputation: 31

Remove duplicate elements from a drop down list using javascript

This is the dropdown list box. I want to remove the duplicate "Apple" using javascript.

<select id="Fruits">
<option value="Apple" >Apple</option>
<option value="Orange">Orange</option>
<option value="Mango">Mango</option>
<option value="Apple" >Apple</option>
</select>

Upvotes: 2

Views: 5897

Answers (2)

ocodo
ocodo

Reputation: 30248

This is @DanDavis answer for reference, I'm adding it as, you know, public service. Plus a bit of formatting and a couple of alternatives to cover similar use cases.

var fruits = document.getElementById("Fruits");

[].slice.call(fruits.options)
  .map(function(a){
    if(this[a.value]){ 
      fruits.removeChild(a); 
    } else { 
      this[a.value]=1; 
    } 
  },{});

If you are working with a select populated by a database (a pretty obvious use case) and the values are ids and the innerText is the duplicates you want to remove. Then instead you'd want:

[].slice.call(fruits.options)
  .map(function(a){
    if(this[a.innerText]){ 
      fruits.removeChild(a); 
    } else { 
      this[a.innerText]=1; 
    } 
  },{}); 

Furthermore, if you want to retain the selected option (it might not be the first occurrence matched.) Try this:

[].slice.call(fruits.options)
  .map(function(a){
    if(this[a.innerText]){ 
      if(!a.selected) fruits.removeChild(a); 
    } else { 
      this[a.innerText]=1; 
    } 
  },{}); 

Upvotes: 3

Xotic750
Xotic750

Reputation: 23472

In ES3 POJS you could do this.

Javascript

function removeDuplicateOptions(selectNode) {
    if (typeof selectNode === "string") {
        selectNode = document.getElementById(selectNode);
    }

    var seen = {},
        options = [].slice.call(selectNode.options),
        length = options.length,
        previous,
        option,
        value,
        text,
        i;

    for (i = 0; i < length; i += 1) {
        option = options[i];
        value = option.value,
        text = option.firstChild.nodeValue;
        previous = seen[value];
        if (typeof previous === "string" && text === previous) {
            selectNode.removeChild(option);
        } else {
            seen[value] = text;
        }
    }
}

removeDuplicateOptions("Fruits");

On jsfiddle

Upvotes: 1

Related Questions