JavaScript移除数组内重复元素的方法
本文实例讲述了JavaScript移除数组内重复元素的方法。分享给大家供大家参考。具体分析如下:
这段JS代码用于从数组中移除重复的元素,比如:['apple','orange','peach','apple','strawberry','orange']去重后返回:s['apple','orange','peach','strawberry']
functionremoveDuplicates(arr){
vartemp={};
for(vari=0;i<arr.length;i++)
temp[arr[i]]=true;
varr=[];
for(varkintemp)
r.push(k);
returnr;
}
//Usage
varfruits=['apple','orange','peach','apple','strawberry','orange'];
varuniquefruits=removeDuplicates(fruits);
//printuniquefruits['apple','orange','peach','strawberry'];
下面的代码可以在浏览器中验证
Removeduplicateelementsfromanarray. <br>
<pre> varfruits=['apple','orange','peach','apple','strawberry','orange'];
</pre>
Note'orange'isduplicateinfruitsarray.Clicktoremoveduplicateelementsfromfruitsarray:<br>
<buttononclick="check()">RemoveDuplicate</button>
<script>
functionremoveDuplicates(arr){
vartemp={};
for(vari=0;i<arr.length;i++)
temp[arr[i]]=true;
varr=[];
for(varkintemp)
r.push(k);
returnr;
}
functioncheck(){
varfruits=['apple','orange','peach','apple','strawberry','orange'];
varuniquefruits=removeDuplicates(fruits);
alert(uniquefruits);
}
</script>
希望本文所述对大家的javascript程序设计有所帮助。