// 数组去重
let arr = ['a', 'b', 'b', 1, 1, 'true', true, true, NaN, NaN, 'NaN', undefined, undefined, null, null];
// 1. 集合
unique1 = arr => [...new Set(arr)]; // 2. 双循环
unique2 = arr => {
let array = [];
arr.forEach(item => {
if (!array.includes(item)) {
array.push(item);
}
})
return array
} // 3. 对象的属性 / Map的key 唯一性
unique3 = arr => {
const map = new Map();
return arr.filter(item => !map.has(item) && map.set(item, 1))
}
unique4 = arr => {
let obj = {}
return arr.filter(item => !obj[typeof item + item] && (obj[typeof item + item] = 1))
} // 4. 排序
unique5 = arr => {
arr = arr.sort()
let res = [arr[0]]
for (let i = 1; i < arr.length; i++) {
if (arr[i] !== arr[i - 1]) {
res.push(arr[i])
}
}
return res
}