You can do it as follows:
var found = []; $("select option").each(function() { if($.inArray(this.value, found) != -1) $(this).remove(); found.push(this.value); });
Try it here , this is a simple approach, we just save an array of the values ββfound, if we did not find the value, add it to the array ( .push() ), if we found this value, this is the hype we found earlier, .remove() it.
Only a <select> traversal is performed once, which minimizes the DOM traversal, which is much more expensive than array operations. We also use $.inArray() instead of .indexOf() , so this works correctly in IE.
If you need a less efficient but shorter solution (just use the first method to illustrate!):
$('select option').each(function() { $(this).prevAll('option[value="' + this.value + '"]').remove(); });
You can test it here , it will remove all siblings with the same value, but it is much more expensive than the first method (DOM Traversal expensive and multiple calls to selector engines here, many more). We use .prevAll() because you cannot just remove .siblings() inside .each() , this will cause some errors in the loop, since it is expecting the next child.
Nick craver
source share