JS数组 并集 交集 差集
现有两个数组
a=[1, 2, 3];b=[2, 4, 5]
,求数组的并集,交集,合集
-
ES5
//并集 let union=a.concat(b.filter(item=>a.indexof(item)==-1))//[1,2,3,4,5] //交集 let intersection=a.filter(item=>b.indexOf(item)!==-1)//[2] //差集 let differece=a.filter(item=>b.indexOf(item)==-1).concat(b.filter(item=>a.indexOf(item)==-1))//[1, 3, 4, 5]
-
Es6
//并集 let union=Array.from(new Set([..a,..b]))//[1,2,3,4,5] //交集 let intersection=Array.from(new Set(a.filter(item=>new Set(b).has(item)))) //差集 let differece=[...Array.from([...a.filter(item=>!new Set(b).has(item)),...b.filter(item=>!new Set(a).has(item))])]////[1, 3, 4, 5]
-
Es7
//并集 let union=a.concat(b.filter(item=>!a.includes(item))) //交集 let intersection=a.filter(item=?a.includes(item)) //差集 let defference=a.concat(b).filter(item=>!a.includes(item)||!b.includes(item))