使用map给数组去重,利用数据结构存值的特点,示例如下
方法1
let list = [11, 22, 333, 11, 33, 66, 555, 444, 222, 11, 333]
function mapuse(arr) {
let map = new Map()
let newList = []
for (let i = 0; i < arr.length; i++) {
if (!map.has(arr[i])) {
map.set(arr[i], true)
newList.push(arr[i])
}
}
return newList
}
console.log(mapuse(list));
方法2
let arrObj = [3, 2, 4, 1, 1, 2, 2, 3, 3]
function doublemapuse(array) {
let map2 = new Map();
for (let item of array) {
if (!map2.has(item)) {
map2.set(item, true);
};
};
return [...map2.keys()]
}
console.log(doublemapuse(arrObj));
方法三
let repeatArr = [];
function nonRepeat(arr) {
let hashMap = new Map();
let result = [];
for(let i = 0; i < arr.length; i++) {
if(hashMap.has(arr[i])) {
repeatArr.push(arr[i]);
} else {
hashMap.set(arr[i], "noRepeat");
}
}
console.log(hashMap,'hashMap');
// hashMap.forEach((value, key) => result.push(key));
hashMap.forEach((value, key) => {
console.log(value, key);
return result.push(key)
});
return result;
}
let array = [1,1,2,3,3,4];
console.log(nonRepeat(array)); // [1,2,3,4]
console.log(repeatArr); // [1,3]
ES6 提供了新的数据结构 Set。它类似于数组,但是成员的值都是唯一的,没有重复的值。Set 本身是一个构造函数,用来生成 Set 数据结构。
数组去重
Array.from 方法可以将 Set 结构转为数组。我们可以专门编写使用一个去重的函数
字符去重
另外 Set 是如此强大,因此使用 Set 可以很容易地实现并集(Union)、交集(Intersect)和差集(Difference)。
参考链接1:map数组去重-CSDN博客