Friday, December 27, 2024
Google search engine
HomeLanguagesJavascriptHow to compute union of JavaScript arrays ?

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

  • Declare both arrays named A and B.
  • Use the spread operator to concat both arrays and store them into sets.
  • Since the set removes the duplicate elements.
  • After removing the duplicate elements, it will display the union of the array elements.

Example: This example implements the spread operator approach.

Javascript




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

  • Here, all elements are stored in a JavaScript object.
  • Storing elements in JavaScript Object is going to remove the duplicate elements.
  • In the end, push all elements in a JavaScript array by using push() method.

Example: This example implements the above approach.

Javascript




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:

Javascript




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).

Javascript




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]

RELATED ARTICLES

Most Popular

Recent Comments