1.遍历数组法
最简单的数组去重,实现思路:新建一数组,遍历传入数组,值不在数组就加入该新数组中;注意点:判断值是否在数组的方法“indexOf”是ES5方法,IE8以下不兼容,需写兼容代码,源码如下:
var arr = ["a","b","c","c","b","d","a","e"];
function del(array){
var n = [];
for(var i=0;i<array.length;i++){
if(n.indexOf(array[i]) == -1){
n.push(array[i])
}
}
return n
}
console.log(del(arr))
结果:["a","b","c","d","e"]
兼容代码块:
if(!Array.prototype.indexOf){
Array.prototype.indexOf = function(item){
var result = -1,a_item = null;
if(this.length ==0){
return result;
}
for(var i = 0;len=this.length;i<len;i++){
a_item = this[i];
if(a_item === item){
result = i;
break;
}
}
return result;
}
}
2.Set去重,ES6方法,简单易懂
function del(array){
var s = new Set(array);
var arr = [];
for(attr of s){
arr.push(attr);
}
return arr;
}
console.log(del(arr))
结果:["a","b","c","d","e"]
3.哈希去重,将数组中的每个元素都挂一个状态,然后循环遍历判断此状态是否存在,然后将符合的元素插入到新数组。
function del(array){
var hash = {};
var res = [];
for(var i = 0; i < array.length; i++){
if(!hash[array[i]]){
hash[array[i]] = true;
res.push(array[i]);
}
}
return res;
}
console.log(del(arr));
结果:["a","b","c","d","e"]
4.对象键值对法
该方法执行的速度快,就是占用的内存大一些;实现思路:新建一js对象以及新数组,遍历传入数组,判断值是否为JS对象的值。注意点:判断是否为JS对象键时,会自动执行“toString()”,不同的键可能会被误认为一样,例如:a[1],a[“a”],解决调用”indexOf”
function del(array){
var n = {},r = [],len = array.length,val,type;
for(var i = 0; i <len;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;
}
console.log(del(arr));
结果:["a","b","c","d","e"]
5.排序后相邻去重
虽然“sort”方法排序结果不怎么靠谱,但是不注重顺序的去重里该缺点无影响。实现思路:给传入数组排序,排序后相同值相邻,然后遍历时新数组只加入不与前一值重复的值。
function del(array){
array.sort();
var re = [array[0]];
for(var i= 0;i<array.length;i++){
if(array[i]!==re[re.length-1]){
re.push(array[i]);
}
}
return re;
}
console.log(del(arr));
结果:["a","b","c","d","e"]