Skip to content

Instantly share code, notes, and snippets.

@Sanchithasharma
Created January 13, 2022 16:53
Show Gist options
  • Save Sanchithasharma/61443ddedc13746df66a7596f90b48b0 to your computer and use it in GitHub Desktop.
Save Sanchithasharma/61443ddedc13746df66a7596f90b48b0 to your computer and use it in GitHub Desktop.
Diff Two Arrays
// Compare two arrays and return a new array with any items only found in one of the two given arrays, but not both. In other words, return the symmetric difference of the two arrays.
// Note: You can return the array with its elements in any order.
function diffArray(arr1, arr2) {
const newArr = [];
filter(arr1, arr2, newArr)
filter(arr2, arr1, newArr)
return newArr;
}
function filter(arr1, arr2, newArr) {
arr1.map(el => {
if(!arr2.includes(el)) {
newArr.push(el)
}
})
}
diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);
@Sanchithasharma
Copy link
Author

function diffArray(arr1, arr2) {
  let newArr = [];
  const canArr = arr1.concat(arr2)
  newArr = canArr.filter(el => {
    return !arr1.includes(el) || !arr2.includes(el)
  })
  console.log(newArr)
  return newArr;
}

diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment