1.Es6的Set数组去重法:(ES6 提供了新的数据结构 Set。它类似于数组,但是成员的值都是唯一的,没有重复的值。)
let aList = [1, 2, 5, 6, 4, 9, 2, 1, 2, 3, 4, 5, 6, 5, 5, 3, 3, 4, 2, 1];
let aList2 = [...new Set(aList)];
console.log(aList2); //1,2,5,6,4,9,3
2.遍历,将值添加到新数组,用indexOf() (该方法是返回数组中元素第一次出现的索引值;如果有,则正常返回索引值;如果检索的内容不存在于数组中,则返回-1) 判断值是否存在,已存在就不添加,达到去重效果。
let testArr = ['1', '2', '3', 1, NaN, NaN, undefined, undefined, null, null, 'a', 'b', 'b'];
let newArray = [];
for (let item of testArr) {
if (newArray.indexOf(item) == -1) {
newArray.push(item)
} else {
console.log('重复了', item)
}
}
console.log(newArray); //["1", "2" , "3" , 1, NaN,NaN, undefined, null, "a", "b"]
3.遍历,将数组的值添加到一个对象的属性名里,并给属性赋值,对象不能添加相同属性名,以这个为依据可以实现数组去重,然后用Object.keys(对象)
返回这个对象可枚举属性组成的数组,这个数组就是去重后的数组
let A = ['1', '2', '3', 1, NaN, NaN, undefined, undefined, null, null, 'a', 'b', 'b'];
const unique = arr => {
let obj = {}
arr.forEach(value => {
obj[value] = 0; //这步新添加一个属性,并赋值,如果不赋值的话,属性会添加不上去
})
return Object.keys(obj); //`Object.keys(对象)`返回这个对象可枚举属性组成的数组,这个数组就是去重后的数组
}
console.log(unique(a)); //["1", "2", "3", "NaN", "undefined", "null", "a", "b"]
4.相比较filter(),forEach()还有一些遍历去实现的方法来说这个方法很简单,是超级好用的js数组去重
let array = [{
id: 1,
value: 1
}, {
id: 2,
value: 2
}, {
id: 3,
value: 2
}, {
id: 4,
value: 3
}, {
id: 5,
value: 4
}];
let obj = {};
array = array.reduce((cur, next) => {
obj[next.value] ? "" : obj[next.value] = true && cur.push(next);
return cur;
}, []);