https://segmentfault.com/a/1190000015923301?utm_source=tag-newest
function arrayNonRepeatfy(arr) {
let hashMap = new Map();
let result = new Array(); // 數(shù)組用于返回結(jié)果
for (let i = 0; i < arr.length; i++) {
if(hashMap.has(arr[i])) { // 判斷 hashMap 中是否已有該 key 值
hashMap.set(arr[i], true); // 后面的true 代表該 key 值在原始數(shù)組中重復(fù)了鸯乃,false反之
} else { // 如果 hashMap 中沒有該 key 值辙浑,添加
hashMap.set(arr[i], false);
result.push(arr[i]);
}
}
return result;
}
let arr = [1, 1, 1, 2, 3, 3, 4, 5, 5, "a", "b", "a"];
console.log(arrayNonRepeatfy(arr)); // [ 1, 2, 3, 4, 5, 'a', 'b' ]
filter
function unique(arr) {
//定義常量 res,值為一個Map對象實例
const res = new Map();
//返回arr數(shù)組過濾后的結(jié)果,結(jié)果為一個數(shù)組
//過濾條件是,如果res中沒有某個鍵耿芹,就設(shè)置這個鍵的值為1
return arr.filter((a) => !res.has(a) && res.set(a, 1))
}