I have a dropdown selector generated from a list and want to filter the options to remove the duplicate entries. e.g. I want to filter ...
You can try the following code, it will remove the duplicates regardless of their position. Here #targetSelect is your target Dropdown
var a = new Array();
$(#targetSelect).children("option").each(function(x){
test = false;
b = a[x] = $(this).text();
for (i=0;i<a.length-1;i++){
if (b ==a[i]) test =true;
}
if (test) $(this).remove();
});
You can do it with a simple loop - there may be a cleverer way to handle this with jQuery selectors that I'm not seeing, though. The following should work:
var usedNames = {};
$("select[name='company'] > option").each(function () {
if(usedNames[this.text]) {
$(this).remove();
} else {
usedNames[this.text] = this.value;
}
});
Edit: Here's a functional-style one-liner that does it with the help of the excellent Underscore.js, although the previous version is almost certainly more efficient:
_.each(_.uniq(_.pluck($("select[name='company'] > option").get(), 'text')), function(name) { $("select[name='company'] > option:contains(" + name + ")").not(":first").remove(); });
You can do something like this:
var previousOption;
$('select[name=company] option').each(function() {
if (this.text == previousOption) $(this).remove();
previousOption= this.text;
});