DEV Community

Rajesh Kumar Yadav
Rajesh Kumar Yadav Subscriber

Posted on

4 2

Intersection and Union of Array in JavaScript

Array and Union

What is union of Arrays?

Union of arrays would represent a new array combining all elements of the input arrays, without repetition of elements.

let arrOne = [10,15,22,80];
let arrTwo = [5,10,11,22,70,90];

// Union of Arrays
let arrUnion = [...new Set([...arrOne, ...arrTwo])];
console.log(arrUnion);
Enter fullscreen mode Exit fullscreen mode

What is intersection of Arrays?

The intersection of two arrays is a list of distinct numbers which are present in both the arrays. The numbers in the intersection can be in any order.

let arrOne = [10,15,22,80];
let arrTwo = [5,10,11,22,70,90];

// Intersection of Arrays
let arrIntersection = arrOne.filter((v) =>{
    return arrTwo.includes(v);
});
console.log(arrIntersection);
Enter fullscreen mode Exit fullscreen mode

Demo -

Top comments (0)

typescript

11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay