这段JS代码用于从数组中移除重复的元素,比如: [‘apple’, ‘orange’, ‘peach’, ‘apple’, ‘strawberry’, ‘orange’] 去重后返回:s [‘apple’, ‘orange’, ‘peach’, ‘strawberry’]
脚本分享网还提供了一个在线去重的工具,如果有需要可以在线使用:
http://tools.75271.com/unique.html
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'];
下面的代码可以在浏览器中验证
Remove duplicate elements from an array. <br> <pre> var fruits = ['apple', 'orange', 'peach', 'apple', 'strawberry', 'orange'];
Note ‘orange’ is duplicate in fruits array. Click to remove duplicate elements from fruits array:
