# Finding union of two sets in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

## 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 ]
Published on 11-Dec-2020 09:36:44