- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Finding union of two sets in JavaScript

## Union Set

Union Set is the set made by combining the elements of two sets. Therefore, the union of sets A and B is the set of elements in A, or B, or both.

**For example −**

If we have two sets denoted by two arrays like this −

const arr1 = [1, 2, 3]; const arr2 = [100, 2, 1, 10];

Then the union set will be −

const union = [1, 2, 3, 10, 100];

We are required to write a JavaScript function that takes in two such arrays of literals and returns their union array.

## Example

Following is the code −

const arr1 = [1, 2, 3]; const arr2 = [100, 2, 1, 10]; const findUnion = (arr1 = [], arr2 = []) => { const map = {}; const res = []; for (let i = arr1.length-1; i >= 0; -- i){ map[arr1[i]] = arr1[i]; }; for (let i = arr2.length-1; i >= 0; -- i){ map[arr2[i]] = arr2[i]; }; for (const n in map){ if (map.hasOwnProperty(n)){ res.push(map[n]); } } return res; }; console.log(findUnion(arr1, arr2));

## Output

Following is the output on console −

[ 1, 2, 3, 10, 100 ]

- Related Questions & Answers
- Get the union of two sets in Java
- Java Program to Calculate union of two sets
- JavaScript Union of two objects
- Cartesian product of two sets in JavaScript
- Adding two Sets in Javascript
- Subtract two Sets in Javascript
- Finding gcd of two strings in JavaScript
- Union of two HashSet in C#
- Finding the continuity of two arrays in JavaScript
- Finding matches in two elements JavaScript
- Finding two golden numbers in JavaScript
- Finding Number of Days Between Two Dates JavaScript
- Merge two sets in Java
- Get the intersection of two sets in Java
- Explain sets in JavaScript?

Advertisements