Skip to content

Instantly share code, notes, and snippets.

@samuelko123
Last active May 14, 2022 01:47
Show Gist options
  • Save samuelko123/4d9a33fe9442ce93b6039bef8370ed5d to your computer and use it in GitHub Desktop.
Save samuelko123/4d9a33fe9442ce93b6039bef8370ed5d to your computer and use it in GitHub Desktop.
Javascript algorithms
/*
Symmetric difference of two sets is the set of elements
which are in either of the two sets but not in both.
e.g.
symmetric_difference([1, 2, 3], [5, 2, 1, 4])
// [3, 5, 4]
*/
function symmetric_difference(...args) {
// logic:
// 1. remove duplicates from each input array
// 2. loop through each elem of each input array
// 2.1. if elem does not exist in output array, push elem into output array
// 2.2. if elem does exist in output array, remove elem from output arra
let result = args.reduce((prev, curr) => {
curr = curr.filter((elem, index, arr) => arr.indexOf(elem) === index)
for (let elem of curr){
if (!prev.includes(elem)){
prev.push(elem)
} else {
prev = prev.filter(x => x !== elem)
}
}
return prev
}, [])
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment