22.Set的实践练习
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script>
let arr = [1, 2, 3, 45, 5, 4, 5, 5, 2, 1, 4, 5];
// 去重
// let = result = [...new Set(arr)]; //Set去重之后会变为一个集合,已经不是原来的数组,需要用...展开运算符变为数组
// console.log(result);
// 交集
let arr2 = [1, 2, 3, 3, 2, 1, 7];
// let s2 = new Set(arr2); //放在循环外面可以优化性能
// let result2 = [...new Set(arr)].filter((item) => {
// if (s2.has(item)) return item;
// });
// 也可这样写
// let result2 = [...new Set(arr)].filter((item) => new Set(arr2).has(item));
// console.log(result2);
// 并集
// let union = [...new Set([...arr, ...arr2])];
// console.log(union);
// 差集
let diff = [...new Set(arr)].filter((item) => !new Set(arr2).has(item));
let diff2 = [...new Set(arr2)].filter((item) => !new Set(arr).has(item));
console.log(diff2);
</script>
</body>
</html>