How to use the push() method In Javascript

  • 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
]


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:

Table of Content

  • Using the spread operator and set
  • Using the push() method
  • Using filter() and concat() Method
  • Using Underscore.js _.union() Function
  • Using reduce() and includes()

Similar Reads

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

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

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

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

Using reduce() and includes()

Using reduce() and includes(), initialize the accumulator with one array, then iterate over the other array. If the value is not already in the accumulator, add it. This method ensures uniqueness while computing the union....