實現(xiàn)方法:1、使用“new Set(數(shù)組)”語句將兩個數(shù)組都轉(zhuǎn)換為set集合類型;2、使用“new Set([…集合1].filter(x => 集合2.has(x)))”語句獲取兩個集合的交集即可,會返回一個包含全部交集元素的新集合。
本教程操作環(huán)境:windows7系統(tǒng)、ECMAScript 6版、Dell G3電腦。
在es6中,可以利用set對象的has() 方法配合數(shù)組的filter()來求兩個數(shù)組的交集。
-
Set是ES6新提供的數(shù)據(jù)結(jié)構(gòu),類似于數(shù)組,但是本身沒有重復(fù)值。利用這一特性,我們可以將數(shù)組轉(zhuǎn)為Set類型進(jìn)行去重,然后使用Array.from方法將其再轉(zhuǎn)為數(shù)組。
-
Set has() 方法指示 Set 對象是否包含指定的值。如果指定的值存在,則返回真,否則返回假。
let a=[1, 2, 3]; let b=[3, 5, 2]; newA = new Set(a); newB = new Set(b); let intersectionSet = new Set([...newA].filter(x => newB.has(x))); console.log(intersectionSet);
可以看出此時,交集元素被包含在一個set集合中返回,可利用Array.from方法將集合轉(zhuǎn)為數(shù)組類型
-
Array.from方法用于將兩類對象轉(zhuǎn)為真正的數(shù)組:類似數(shù)組的對象(array-like object)和可遍歷(iterable)的對象(包括 ES6 新增的數(shù)據(jù)結(jié)構(gòu) Set 和 Map)。
let intersectionSet = Array.from(new Set([...newA].filter(x => newB.has(x)))); console.log(intersectionSet);
擴展知識:求并集/差集
let a = new Set([1, 2, 3]); let b = new Set([3, 5, 2]); // 并集 let unionSet = new Set([...a, ...b]); //[1,2,3,5] // ab差集 let differenceABSet = new Set([...a].filter(x => !b.has(x)));
【