步驟:1、將兩個(gè)數(shù)組分別轉(zhuǎn)為set類(lèi)型,語(yǔ)法“newA=new Set(a);newB=new Set(b);”;2、利用has()和filter()求差集,語(yǔ)法“new Set([…newA].filter(x =>!newB.has(x)))”,差集元素會(huì)被包含在一個(gè)set集合中返回;3、利用Array.from將集合轉(zhuǎn)為數(shù)組類(lèi)型,語(yǔ)法“Array.from(集合)”。
前端(vue)入門(mén)到精通課程:進(jìn)入學(xué)習(xí)
Apipost = Postman + Swagger + Mock + Jmeter 超好用的API調(diào)試工具:點(diǎn)擊使用
本教程操作環(huán)境:windows7系統(tǒng)、ECMAScript 6版、Dell G3電腦。
找出2個(gè)數(shù)組中不同項(xiàng),就是獲取兩個(gè)數(shù)組的差集。
在es6中,可以借助set對(duì)象的has()方法來(lái)求兩個(gè)數(shù)組的差集。
實(shí)現(xiàn)步驟:
步驟1、將兩個(gè)數(shù)組分別轉(zhuǎn)為set類(lèi)型
let a=[1, 2, 3]; let b=[3, 5, 2]; newA = new Set(a); newB = new Set(b);
步驟2:求差集
利用set對(duì)象的has() 方法配合數(shù)組的filter()來(lái)求兩個(gè)數(shù)組的差集。
-
Set has() 方法指示 Set 對(duì)象是否包含指定的值;如果指定的值存在,則返回真,否則返回假。
-
而filter()方法用于過(guò)濾數(shù)組,返回符合條件(為真)的元素。
實(shí)現(xiàn)代碼
let a=[1, 2, 3]; let b=[3, 5, 2]; newA = new Set(a); newB = new Set(b); console.log(newA); console.log(newB); let differenceABSet = new Set([...newA].filter(x => !newB.has(x))); console.log("差集為:"); console.log(differenceABSet);
可以看出此時(shí),差集元素被包含在一個(gè)set集合中返回,我們可以將其轉(zhuǎn)為數(shù)組類(lèi)型。
步驟3:利用Array.from方法將集合轉(zhuǎn)為數(shù)組類(lèi)型
let a=[1, 2, 3]; let b=[3, 5, 2]; newA = new Set(a); newB = new Set(b); console.log(newA); console.log(newB); let differenceABSet = Array.from(new Set([...newA].filter(x => !newB.has(x)))); console.log("差集為:"); console.log(differenceABSet);
說(shuō)明:Array.from方法用于將兩類(lèi)對(duì)象轉(zhuǎn)為真正的數(shù)組:類(lèi)似數(shù)組的對(duì)象(array-like object)和可遍歷(iterable)的對(duì)象(包括 ES6 新增的數(shù)據(jù)結(jié)構(gòu) Set 和 Map)。
擴(kuò)展知識(shí):求并集/交集
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 intersectionSet = new Set([...a].filter(x => b.has(x)));
【