使用javascript从下拉列表中删除重复的元素 [英] Remove duplicate elements from a drop down list using javascript
问题描述
这是下拉列表框。我想使用javascript删除重复的Apple。
This is the dropdown list box. I want to remove the 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>
推荐答案
这是@DanDavis答案供参考,我是你知道,加入公共服务。加上一些格式化和几个替代方案来涵盖类似的用例。
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;
}
},{});
如果您正在使用由数据库填充的select(非常明显的用例)和值 ids
, innerText
是您要删除的重复项。然后你想要:
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;
}
},{});
这篇关于使用javascript从下拉列表中删除重复的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!