Set方法
Set 构造函数能让你创建 Set 对象,其可以存储任意类型的唯一值,无论是 primitive values 或者对象引用。
创建set集合
new Set([xxx])
如果传递一个可迭代对象,它的所有元素将不重复地被添加到新的 Set中。
const s1 = new Set([1,2,3,4,5,6,7,3,6])
console.log(s1)
如果不指定此参数或其值为null,则新的 Set为空。
如果存放的是原始值:会转换成字符串对象,再进行存储。
const s1 = new Set("ashfdkjhadj")
console.log(s1)
// 等同于
console.log(new String("ashfdkjhadj"))
set本身就是可迭代对象,可以使用扩展运算符和set特性去做到数组去重,也可以做到字符串去重。
const arr = [1,1,2,5,75,48,34,88,75,55,88,66,74,34]
const result = [...new Set(arr)]
const str = "hello world";
const s = [...new Set(str)].join("")
知道了以上特点,用Set方法求交集并集差集,也是简简单单的了
首先创建两个数组(后面求交集并集差集)
const arr2 = [55, 34, 11, 76, 78, 10, 19, 88, 99, 99]
const arr1 = [12, 34, 55, 33, 11, 33, 5, 12]
用set将这两个数组去重
const one = [...new Set(arr1)]
const two = [...new Set(arr2)]
将数组one和数组two合并,并用set方法去重
const three = one.concat(two)
console.log('并集', [...new Set(three)])
交集,运用filter方法过滤,然后用set方法去重并转为新数组
let jiao = [...new Set(one.filter(n => new Set(arr2).has(n)))]
console.log('交集', jiao)
差集,运用filter方法过滤,将数组1和数组2分别过滤,然后用set方法去重并转为新数组
let difference = [...new Set(one.filter(n => !new Set(arr2).has(n)))]
let difference2 = [...new Set(two.filter(n => !new Set(arr1).has(n)))]
console.log('差集', difference.concat(difference2))
整体代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
const arr2 = [55, 34, 11, 76, 78, 10, 19, 88, 99, 99]
const arr1 = [12, 34, 55, 33, 11, 33, 5, 12]
// 用set完成两个数组的交集,并集和差集
const one = [...new Set(arr1)]
const two = [...new Set(arr2)]
const three = one.concat(two)
console.log('并集', [...new Set(three)])
let jiao = [...new Set(one.filter(n => new Set(arr2).has(n)))]
let difference = [...new Set(one.filter(n => !new Set(arr2).has(n)))]
let difference2 = [...new Set(two.filter(n => !new Set(arr1).has(n)))]
console.log('交集', jiao)
console.log('差集', difference.concat(difference2))
</script>
</body>
</html>