JavaScript移除数组内重复元素的方法
编程学习 2021-07-04 21:47www.dzhlxh.cn编程入门
这篇文章主要介绍了JavaScript移除数组内重复元素的方法,实例分析了javascript遍历数组及删除等操作的相关技巧,需要的朋友可以参考下
本文实例讲述了JavaScript移除数组内重复元素的方法。分享给大家供大家参考。具体分析如下:
这段JS代码用于从数组中移除重复的元素,比如: ['apple', 'orange', 'peach', 'apple', 'strawberry', 'orange'] 去重后返回:s ['apple', 'orange', 'peach', 'strawberry']
代码如下:
function removeDuplicates(arr) {
var temp = {};
for (var i = 0; i < arr.length; i++)
temp[arr[i]] = true;
var r = [];
for (var k in temp)
r.push(k);
return r;
}
//Usage
var fruits = ['apple', 'orange', 'peach', 'apple', 'strawberry', 'orange'];
var uniquefruits = removeDuplicates(fruits);
//print uniquefruits ['apple', 'orange', 'peach', 'strawberry'];
var temp = {};
for (var i = 0; i < arr.length; i++)
temp[arr[i]] = true;
var r = [];
for (var k in temp)
r.push(k);
return r;
}
//Usage
var fruits = ['apple', 'orange', 'peach', 'apple', 'strawberry', 'orange'];
var uniquefruits = removeDuplicates(fruits);
//print uniquefruits ['apple', 'orange', 'peach', 'strawberry'];
狼蚁网站SEO优化的代码可以在浏览器中验证
代码如下:
Remove duplicate elements from an array. <br>
<pre> var fruits = ['apple', 'orange', 'peach', 'apple', 'strawberry', 'orange'];
</pre>
Note 'orange' is duplicate in fruits array. Click to remove duplicate elements from fruits array:<br>
<button onclick="check()">Remove Duplicate</button>
<script>
function removeDuplicates(arr) {
var temp = {};
for (var i = 0; i < arr.length; i++)
temp[arr[i]] = true;
var r = [];
for (var k in temp)
r.push(k);
return r;
}
function check() {
var fruits = ['apple', 'orange', 'peach', 'apple', 'strawberry', 'orange'];
var uniquefruits = removeDuplicates(fruits);
alert(uniquefruits);
}
</script>
<pre> var fruits = ['apple', 'orange', 'peach', 'apple', 'strawberry', 'orange'];
</pre>
Note 'orange' is duplicate in fruits array. Click to remove duplicate elements from fruits array:<br>
<button onclick="check()">Remove Duplicate</button>
<script>
function removeDuplicates(arr) {
var temp = {};
for (var i = 0; i < arr.length; i++)
temp[arr[i]] = true;
var r = [];
for (var k in temp)
r.push(k);
return r;
}
function check() {
var fruits = ['apple', 'orange', 'peach', 'apple', 'strawberry', 'orange'];
var uniquefruits = removeDuplicates(fruits);
alert(uniquefruits);
}
</script>
希望本文所述对大家的javascript程序设计有所帮助。