jQuery Remove Select Tag Duplicates
Remove duplicate options from a select element with a short jQuery loop.
A dropdown filled from a data source can end up with the same text more than once. This snippet removes the repeats.
js
var usedDisplayNames = {};
$("select[name='tagname'] > option").each(function () {
if (usedDisplayNames[this.text]) {
$(this).remove();
} else {
usedDisplayNames[this.text] = this.value;
}
});
usedDisplayNames is an object that maps option text (the key) to option value. The code loops over each option in the select. If the text is already in the object, the option is removed. Otherwise it is added to the object.