Union of Arrays in JavaScript

Union of arrays would represent a new array combining all elements of the input arrays, without repetition of elements.

Two ways are described in this tutorial. There both involve a bit of ES6 features.

ES6 Features Used

  • Set : A Set object allows to store unique values. A Set object can be created from an array (or any iterable object). If the array has duplicate elements, they are eliminated.

    // creating Set from an array
    var set_ob = new Set([1, 2, 3, 3, 4, 5, 5]);
    
    // [1, 2, 3, 4, 5]
    // duplicates eliminated
    console.log(set_ob);
    

    To know more about the Set object you can refer An Introduction to Sets in JavaScript.

  • Spread Operator : The spread operator ... automatically "expands" an array (or any iterable object) into its individual elements. These individual elements can be used in situations where multiple parameters are expected.

    // merging of arrays using spread operator
    
    var arr1 = [1, 2, 3, 4];
    var arr2 = [5, 6, 7];
    
    // create new array
    // using spread operator to expand each array into individual elements
    var arr3 = [ ...arr1, ...arr2 ];
    
    // [1, 2, 3, 4, 5, 6, 7]
    console.log(arr3);
    

    To know more about the spread operator you can refer JavaScript Spread Operator.

Method 1 - Merging & Eliminating Duplicates

  • We first merge all arrays into one single array
  • We then use the merged array to create a Set. This would eliminate duplicates.
  • We then loop over the Set and create the final array.
var array_first = [1, 2, 3, 4];
var array_second = [3, 4, 5, 6];

// concatenation of the arrays
var concat_array = array_first.concat(array_second);

// create Set, eliminate duplicates
var set_ob = new Set(concat_array);

// final array that holds union
var array_union = [];

// iterate through each element of Set
// push each element into final array
for(var element of set_ob) {    
    array_union.push(element); 
}

// [1, 2, 3, 4, 5, 6]
console.log(array_union);

Method 2 - Using Spread Operator to Avoid Looping

The spread operator is a good way to eliminate looping. The same work is done, but with a shorter syntax.

  • We use spread operator to merge arrays.
  • We then create a Set from the merged array. This eliminates duplicates.
  • Then again use spread operator to create an array from the Set.
var array_first = [1, 2, 3, 4];
var array_second = [3, 4, 5, 6];

// merged array
var concat_array = [...array_first, ...array_second];

// new array that holds union
// spread expands the Set into its individual values
var array_union = [...new Set(concat_array)];

// [1, 2, 3, 4, 5, 6]
console.log(array_union);
Intersection and Difference of Arrays in JavaScript