es6 Set

ES6提供了数据结构Set。类似于数组,但是没有重复值。

Set本身是一个构造函数,用来生成Set数据结构

let a = new Set([1, 2, 3])
let b = new Set([4, 3, 2])

// 并集
let union = new Set([...a, ...b])
console.log(union) // Set(4) {1, 2, 3, 4}
// 交集
let intersect = new Set([...a].filter(x => b.has(x)))
console.log(intersect) // Set(2) {2, 3}
// 差集
let difference = new Set([...a].filter(x => !b.has(x)))
console.log(difference) // Set(1) {1}

数组的map()filter()可用于Set

    let set1 = new Set([1, 2, 3])
    set1 = new Set([...set1].map(x => x * 2))
    console.log(set1) // Set(3) {2, 4, 6}
    let set2 = new Set([1, 2, 3, 4, 5])
    set2 = new Set([...set2].filter(x => (x % 2) === 0))
    console.log(set2) // Set(2) {2, 4}

你可能感兴趣的:(es6 Set)