es6 in the implementation of Set union (Union), intersection (Intersect) and difference (Difference)

ES6 provides a new data structure Set. It is similar to an array, but the value of the member is unique, no duplicate values.
Set itself is a constructor to generate Set data structure. Map and filter arrays can also be an indirect method for the Set. Therefore, use the Set can be easily achieved union (Union), intersection (Intersect) and difference (Difference).

let a = new Set(["北京", "上海", "深圳"]);
let b = new Set(["广州", "深圳", "上海"]);
 
// 并集
let union = new Set([...a, ...b]);
// Set {"北京", "上海", "深圳", "广州"}
 
// 交集
let intersect = new Set([...a].filter(item => b.has(item)));
// set {"上海", "深圳"}
 
// 差集
let difference1 = new Set([...a].filter(item => !b.has(item)));
// Set {"北京"}
let difference2 = new Set([...b].filter(item => !a.has(item)));
// Set {"广州"}

Guess you like

Origin blog.csdn.net/qq_36711388/article/details/89819487