数组去重的几种方法
方法一:
对象键值对处理(推荐)
let ary = [1, 2, 3 ,2 ,1 ,3 ,3 ,1 ,2];
let obj = {};
for (let i = 0 ;i< ary.length;i++){
let item = ary[i];
if(obj[item] !== undefined){
ary.splice(i,1);
i--;
continue;
}
obj[item] = item;
}
console.log(obj); ==>[1,2,3]
方法二:
include方法检测是否存在当前项
let ary = [1, 2, 3 ,2 ,1 ,3 ,3 ,1 ,2];
let newAry = [];
for(let i=0,i<ary.length;i++){
let item = ary[i];
if (newAry.includes(item)){
continue;
}
newAry.push(item);
}
console.log(newAry); ==>[1,2,3]
方法三:
基于ES6的Set(对应的Map)实现去重(最简单,如需快速去重)
let ary = [12, 23, 12, 15, 25, 23, 25, 14, 16];
ary = [...new Set(ary)];
console.log(ary); ==>[1,2,3]
方法四:
不创建空数组 不使用includes/indexOf等IE6/7/8不兼容的方法,该方法存在数组塌陷问题( 在对数组进行操作的时候,会使数组的长度产生变化,同时操作的数组那个项的下一个索引会被跳过,从而造成数组的某项会被跳过,这种叫做数组塌陷现象。),所以在删除 j 项后,做一次j–,来解决此问题。
var ary = [1, 2, 3 ,2 ,1 ,3 ,3 ,1 ,2];
for (var i= 0; i<ary.length;i++){
var item = ary[i];
for (var j = i+1; j<ary.length;j++){
var compare = ary[j];
if(compare === item){
ary.splice(j,1);
j--;
}
}
}
console.log(ary); ==>[1,2,3]
方法五:
利用排序+正则
let ary = [1, 2, 3 ,2 ,1 ,3 ,3 ,1 ,2];
ary.sort((a, b) => a - b);
let str = ary.join('@') + '@';
let reg = /(\d+@)\1*/g;
ary = [];
str.replace(reg, (n, m) => {
m = Number(m.slice(0, m.length - 1));
ary.push(m);
});
console.log(ary); ==>[1,2,3]