<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>javascript数组去重算法-----3</title>
</head>
<body>
<script>
var arr = [1,1,2,2,3,2,2,3,3,1,1,4,4,5,6];
function unique(array){
var n = [];
var a = {};
for (var i = 0; i < array.length; i++) {
if (!a[array[i]]) {
a[array[i]] = true;
n.push(array[i])
};
}
return n
}
var cc =unique(arr);
console.log(cc)
//利用对象的特性,存在的向设为true,并且添加的数组,否则不添加
</script>
</body>
</html>
扩展:1模块化,2返回一个对象,对象中包括已去重的数组和每个数字的多少;代码如下:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
var a = [1,2,3,4,5,6,6,6,7,7,7,3,3,3]; var uniqueModule = (function(){
function unique(arr){
var n = [];
var hash = {};
for(var i = 0;i<arr.length;i++){
if(!hash[arr[i]]){
hash[arr[i]] = 1;
n.push(arr[i]);
}else{
hash[arr[i]]++;
}
}
return {
n:n,
hash:hash
};
}
return {
unique:unique
}
}());
console.log(uniqueModule.unique(a));
</script>
</body>
</html>