html - Remove duplicate elements from a drop down list using javascript -


this dropdown list box. want remove 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> 

this @dandavis answer reference, i'm adding as, know, public service. plus bit of formatting , couple of alternatives 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 working select populated database (a pretty obvious use case) , values ids , innertext duplicates want remove. 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 want retain selected option (it might not 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;      }    },{});  

Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -