Skip to content

Latest commit

 

History

History
33 lines (21 loc) · 1.56 KB

README.md

File metadata and controls

33 lines (21 loc) · 1.56 KB

Array intersection, difference and union in ES6

For all the examples, we have two arrays, A let arrA=[1,3,4,5] & B let arrB=[1,2,5,6,7]

Intersection

js array intersection The intersection will give us the elements that both arrays share in common, in this case the result must be [1,5].

let intersection = arrA.filter(x => arrB.includes(x));

Difference

js array difference The difference will output the elements from array A that are not in the array B. The result will be [3,4].

let difference = arrA.filter(x => !arrB.includes(x));

Symmetrical Difference

js array symmetrical difference In this case, you will get an array containing all the elements of arrA that are not in arrB and vice-versa, so the result should be [2,3,4,6,7].

let difference = arrA.filter(x => !arrB.includes(x)).concat(arrB.filter(x => !arrA.includes(x)));

Union

js array union The union must be the simplest of them all, at the end, the result should be all the elements from A, all from B, or both like this [1,2,3,4,5,6,7].

let union = [...arrA, ...arrB];

But, there is a problem is that if we use spread operator, we will get elements duplicated, so it’s no theoretically an union. For doing this we have can use a Set to help us out:

let union = [...new Set([...arrA, ...arrB])];