-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path22.union_arr.js
More file actions
30 lines (26 loc) · 761 Bytes
/
22.union_arr.js
File metadata and controls
30 lines (26 loc) · 761 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// 22. Write a JavaScript program to compute the union of two arrays.
function union(arr1, arr2) {
const newArr = ([...arr1, ...arr2])
const uniqueArr = ([...new Set(newArr)])
return (uniqueArr)
}
console.log("Union of two Array is : ", union([1, 2, 3], [100, 2, 1, 10]));
// another method
function union1(arr1, arr2) {
const result = [];
const map = {}
arr1.forEach(element => {
if (!map[element]) {
map[element] = true;
result.push(element);
}
});
arr2.map((element) => {
if (!map[element]) {
map[element] = true;
result.push(element);
}
})
return result;
}
console.log("Union of two arrays is: ", union1([1, 2, 3], [100, 2, 1, 10]));