Intersection and Union of Array in JavaScript

rajeshkumaryadavdotcom

Rajesh Kumar Yadav

Posted on September 20, 2021

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 -

💖 💪 🙅 🚩
rajeshkumaryadavdotcom
Rajesh Kumar Yadav

Posted on September 20, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Javascript: async/await
javascript Javascript: async/await

November 28, 2024

How to Get a Job in JavaScript
undefined How to Get a Job in JavaScript

November 5, 2024

Your own Promise.all
javascript Your own Promise.all

November 12, 2024