数组去重
数组去重的三种方式
1、利用对象属性不能重复的特性
该方法适用于字符串或number类型的数组去重
var arr = [1,2,2,3,1,5,6,3];
var obj = {};
arr.forEach(p => {
obj[p] = 0;
})
arr = Object.keys(obj).map(p => parseInt(p));
console.log(arr); // [1,2,3,5,6]
2、利用Set对象去重
Set是值的集合,可以存储任意类型的唯一值
var arr = [1,2,2,3,1,5,6,3];
var set = new Set(arr);
arr = [...set];
console.log(arr); //[1,2,3,5,6]
3、利用includes实现任意数组去重
var arr = [1,2,2,3,1,5,6,3];
var newarr = [];
for(var i = 0; i < arr.length; i ++){
if(!newarr.includes(arr[i])){
newarr.push(arr[i]);
}
}
console.log(newarr); //[1,2,3,5,6]
转载自:https://segmentfault.com/a/1190000042552912