Javascript Array Find Difference between two arrays

Description

Javascript Array Find Difference between two arrays

function diffArray(arr1, arr2) {
  var mergedArr = arr1.concat(arr2);
  var uniqueArr = [];
  // Same, same; but different.

  var newArr = [];
  var matchFound = false;
  var itemFound = "";
  var i, j;/* ww  w. j  av  a  2 s  . com*/
  
  var arrLargest = [];
  var arrSmallest = [];
  
  // To loop through all values need to set the largest array as the main loop, to ensure all values covered.
  if (arr1.length > arr2.length) {
    arrLargest = arr1;
    arrSmallest = arr2;
  } else {
    arrLargest = arr2;
    arrSmallest = arr1;
  }

  for (i = 0; i < arrLargest.length; i++) { 
    var result = arrSmallest.indexOf(arrLargest[i]);
    // if the element in largest array not found in the smallest array, add to new array.
    if (result === -1) {
      newArr.push(arrLargest[i]);     
    }
  }
  
  for (i = 0; i < arrSmallest.length; i++) { 
    var result = arrLargest.indexOf(arrSmallest[i]);
    // if the element in largest array not found in the smallest array, add to new array.
    if (result === -1) {
      newArr.push(arrSmallest[i]);     
    }
  }
  return newArr;
}

console.log(diffArray(["A", "B", "C", "D", "E"], ["A", "B", "C", "D", "F"]));



PreviousNext

Related