<!DOCTYPE html>
<html lang="en">
<head>
<title>js数组去重的算法实现</title>
</head>
<body>
<script>
//两个for循环,效率比较低
Array.prototype.unique1 = function() {
var res = [this[0]];
for(var i = 1; i < this.length; i++){
var repeat = false;
for(var j = 0; j < res.length; j++){
if(this[i] === res[j]){
repeat = true;
break;
}
}
if(!repeat){
res.push(this[i]);
}
}
return res;
};
var arr = [0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 6, '1'];
console.log(arr.unique1());
//indexOf
Array.prototype.unique1s = function() {
var res = [this[0]];
for(var i = 1; i < this.length; i++){
if(res.indexOf(this[i]) == -1){
res.push(this[i]);
}
}
return res;
};
var arr = [0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 6, '1'];
console.log(arr.unique1s());
//使用一个空对象,只需要一个for循环,效率高(不能区分1和'1')
Array.prototype.unique2 = function(){
var res = [];
var json = {};
for(var i = 0; i < this.length; i++){
if(!json[this[i]]){
res.push(this[i]);
json[this[i]] = 1;
}
}
return res;
};
//能区分1和'1'
function unique3(array){
var n = {}, r = [], len = array.length, val, type;
for (var i = 0; i < array.length; i++) {
val = array[i];
type = typeof val;
if (!n[val]) {
n[val] = [type];
r.push(val);
} else if (n[val].indexOf(type) < 0) {
n[val].push(type);
r.push(val);
}
}
return r;
}
var arr = [0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 6, '1'];
console.log(arr.unique2());
var arr = [0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 6, '1'];
console.log(unique3(arr));
//es6提供的new Set也可以去重
var items = new Set(arr);
console.log(Array.from(items));
</script>
</body>
</html>
js数组去重的算法实现
最新推荐文章于 2024-05-17 18:03:51 发布