OneBite.Dev - Coding blog in a bite size

find the union of two arrays in Javascript

Code snippet on how to find the union of two arrays in Javascript

function unionOfArrays(arr1, arr2) {
  
  let unionArr = arr1;
  
  for (let i = 0; i < arr2.length; i++) {
      let element = arr2[i];
      if (unionArr.indexOf(element) === -1) {
          unionArr.push(element);
      }
  }
  
  return unionArr;

}

This code iterates through each element of the second array and adds it to a union array if it is not already present in it. The union array is initially set to the first array and is returned at the end. The indexOf() method is used to check if an element is present in the union array. The loop continues until the last element of the second array is checked. If it is not present, it is added to the union array and the union array is returned.

javascript