Open In App

How to compute union of JavaScript arrays ?

Given two arrays containing array elements and the task is to compute the union of both arrays with the help of JavaScript.

These are the methods to solve this problem which are discussed below:



Approach 1:  Using the spread operator and set

Example: This example implements the spread operator approach.




let A = [7, 2, 6, 4, 5];
let B = [1, 6, 4, 9];
 
function GFG_Fun() {
    let union = [...new Set([...A, ...B])];
    console.log("Union is: " + union);
}
 
GFG_Fun();

Output

Union is: 7,2,6,4,5,1,9


Approach 2: Using the push() method

Example: This example implements the above approach.




let A = [7, 2, 6, 4, 5];
let B = [1, 6, 4, 9];
 
function computeUnion(a, b) {
    let object = {};
 
    for (let i = a.length - 1; i >= 0; --i)
        object[a[i]] = a[i];
 
    for (let i = b.length - 1; i >= 0; --i)
        object[b[i]] = b[i];
 
    let ret = [];
 
    for (let i in object) {
        if (object.hasOwnProperty(i))
            ret.push(object[i]);
    }
 
    return ret;
}
 
console.log(computeUnion(A, B));

Output
[
  1, 2, 4, 5,
  6, 7, 9
]


Approach 3: Using filter() and concat() Method

The JavaScript Array concat() Method is used to merge two or more arrays together and filter() method used to create a new array from a given array consisting of only those elements from the given array which satisfy a condition set by the argument method

Example:




let A = [7, 2, 6, 4, 5];
let B = [1, 6, 4, 9];
function GFG_Fun() {
    let newArr =A.concat(B);
    newArr.sort();
    let unionArr = newArr.filter((value, index) =>
                   newArr.indexOf(value) === index);
    console.log(unionArr);
}
 
GFG_Fun();

Output
[
  1, 2, 4, 5,
  6, 7, 9
]


Approach 4: Using Underscore.js _.union() Function

The _.union() function is used to take n number of arrays and return a new array with the unique terms in all those arrays (union of all array).




const _ = require('underscore')
let A = [7, 2, 6, 4, 5];
let B = [1, 6, 4, 9];
function GFG_Fun() {
    let union = _.union(A,B)
    console.log("Union is: " + union);
}
GFG_Fun();

Output:

[1,2,4,5,6,7,9]


Article Tags :