1.indexOf去重(单数组)
(核心思想:把原数组循环遍历出来的每一项push到新的数组里,如果有相同的元素,就不会再进行push操作)
直接上代码
let mobileArrAll = ['华为HUAWEI', 'VIVO', 'IQOO', '华为HUAWEI', 'OPPO', 'VIVO', '小米XIAOMI', '荣耀HONOR', '真我realme', 'IQOO', '一加Oneplus', 'SAMSUNG三星'];
function dupArrHandle(arr) {
var newArr = [];
for (let i = 0; i < arr.length; i++) {
const item = arr[i];
if (newArr.indexOf(item) === -1) {
newArr.push(item)
}
}
return newArr;
}
mobileArrAll = dupArrHandle(mobileArrAll);
console.log(mobileArrAll, 1); // 打印结果为 ["华为HUAWEI","VIVO","IQOO" ,"OPPO" ,"小米XIAOMI","荣耀HONOR" ,"真我realme","一加Oneplus", "SAMSUNG三星"]
2.new Set()去重(单数组)
(核心思想:把一个类数组转为一个Array类型的数组,再用es6的new Set()方法去重),ok这里
直接上代码
// 2.new Set() 去重(单数组)
// .(核心思想:把类原数组转化为真正的数组,再进行es6的数组去重方法)
let mobileNewSet = ['华为HUAWEI', 'VIVO', 'IQOO', '华为HUAWEI', 'OPPO', 'VIVO', '小米XIAOMI', '荣耀HONOR', '真我realme', 'IQOO', '一加Oneplus', 'SAMSUNG三星'];
mobileNewSet = new Set(Array.from(mobileNewSet));
console.log(mobileNewSet, 2); // 打印结果为 ["华为HUAWEI","VIVO","IQOO" ,"OPPO" ,"小米XIAOMI","荣耀HONOR" ,"真我realme","一加Oneplus", "SAMSUNG三星"]
3.new Map()去重
(1).(单数组)
.(核心思想:用es6的new Map()方法,将原数组过滤,返回一个 没有找到item并且给新的数组设置一下原数组对应的item 元素 和第一个去重的原理一致)
直接上代码
let mobileNewMap = ['华为HUAWEI', 'VIVO', 'IQOO', '华为HUAWEI', 'OPPO', 'VIVO', '小米XIAOMI', '荣耀HONOR', '真我realme', 'IQOO', '一加Oneplus', 'SAMSUNG三星'];
let map = new Map();
mobileNewMap = mobileNewMap.filter(item => !map.has(item) && map.set(item))
console.log(mobileNewMap, 3);// 打印结果为 ["华为HUAWEI","VIVO","IQOO" ,"OPPO" ,"小米XIAOMI","荣耀HONOR" ,"真我realme","一加Oneplus", "SAMSUNG三星"]
(2).(数组包对象)
let mobileNewMapObj = [{ name: '华为HUAWEI', id: 1 }, { name: 'VIVO', id: 2 }, { name: 'IQOO', id: 3 }, { name: '华为HUAWEI', id: 1 }, { name: 'OPPO', id: 5 }, { name: 'VIVO', id: 2 }, { name: '小米XIAOMI', id: 7 }, { name: '小米XIAOMI', id: 7 }, { name: '一加Oneplus', id: 8 }, { name: 'SAMSUNG三星', id: 9 }];
let maps = new Map();
mobileNewMapObj = mobileNewMapObj.filter((item) => !maps.has(item.id) && maps.set(item.id, item));
console.log(mobileNewMapObj, 4);
5.reduce去重(核心思想:创建一个对象,判断里面是否有数组元素的id,如果没有就往里面添加,并且往新数组里面添加数据,反之跳过添加)
直接上代码
let mobileNewReduce = [{ name: '华为HUAWEI', id: 1 }, { name: 'VIVO', id: 2 }, { name: 'IQOO', id: 3 }, { name: '华为HUAWEI', id: 1 }, { name: 'OPPO', id: 5 }, { name: 'VIVO', id: 2 }, { name: '小米XIAOMI', id: 7 }, { name: '小米XIAOMI', id: 7 }, { name: '一加Oneplus', id: 8 }, { name: 'SAMSUNG三星', id: 9 }];
let obj = {};
const mobileNewReduces = mobileNewReduce.reduce((lastArr, item, index, primaryArr) => {
obj[item.id] ? '' : obj[item.id] = item.id && lastArr.push(item);
return lastArr
}, initLastArr = [])
console.log(mobileNewReduces, 5);