This is the dropdown list box. I want to remove the duplicate \"Apple\" using javascript.
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;
}
},{});