Es6中关于Set新特性的应用练习
-
数组的去重
方案一:
let arr1 = [1, 1, 3, 4, 6, 7, 4, 9] let s= new Set(arr1) // 这里得到的值并不是最终去重后的数组 let newArray=Array.from(s)
注意:new Set() 的返回值类型是一个Object类型,所以第二步得到的并不是最终去重后的代码
方案二:利用Es6的展开运算符
let arr1 = [1, 1, 3, 4, 6, 7, 4, 9]
// 数组去重
let s = [...new Set(arr1)] // 将对象直接展开放入数组中
-
取出两个数组中元素的交集
let arr1 = [1, 1, 3, 4, 6, 7, 4, 9] let arr2 = [2, 3, 4, 5, 65, 7, 4, 1] //取数组中的元素的交集 let contact = [...new Set(arr1)].filter((item) => new Set(arr2).has(item)) console.log(contact)
-
取出两个数组中元素的并集
let arr1 = [1, 1, 3, 4, 6, 7, 4, 9] let arr2 = [2, 3, 4, 5, 65, 7, 4, 1] //取出数组中元素的并集 let union = [...new Set([...new Set(arr1), ...new Set(arr2)])] console.log(union)
-
取出两个数组中元素的差集
let arr1 = [1, 1, 3, 4, 6, 7, 4, 9]
let arr2 = [2, 3, 4, 5, 65, 7, 4, 1]
//取出数组中元素的差集
let diff = [...new Set(arr1)].filter((item) => !new Set(arr2).has(item))
console.log(diff)