union of two arrays javascript

To perform the union of two arrays in JavaScript, you can follow these steps:

  1. Declare two arrays, let's call them array1 and array2, with the elements you want to combine.
  2. Create a new empty array to store the union of the two arrays, let's call it unionArray.
  3. Concatenate the two arrays using the concat() method in JavaScript. This will combine the elements of array1 and array2 into a single array.
  4. To remove any duplicate elements from the unionArray, you can use the filter() method in JavaScript. Inside the filter() method, you can use the indexOf() method to check if the current element is the first occurrence of that element in the array.
  5. Finally, you can assign the filtered array back to the unionArray variable.

Here is an example of how you can perform the union of two arrays in JavaScript:

let array1 = [1, 2, 3];
let array2 = [2, 3, 4, 5];

let unionArray = array1.concat(array2).filter((elem, index, self) => {
  return index === self.indexOf(elem);
});

console.log(unionArray);

In this example, the output will be [1, 2, 3, 4, 5] as it contains all the unique elements from array1 and array2.