OneBite.Dev - Coding blog in a bite size

find the unique elements in two arrays in Javascript

Code snippet on how to find the unique elements in two arrays in Javascript

function findUniqueElements(arr1, arr2) {
  let concatArray = arr1.concat(arr2);
  let uniqueArray = concatArray.filter(function(item, index){
    return concatArray.indexOf(item) >= index; 
  });
  return uniqueArray;
}

This code finds the unique elements in two arrays. First, it combines the two arrays into a single array using the “concat()” method. Next, it uses the “filter()” method to loop through the combined array and compare each element to the rest of the array. If the index of the value is greater than or equal to the current index, that value is included in the unique array. Finally, the unique array is returned.

javascript