Skip to content

Instantly share code, notes, and snippets.

@Kcko
Last active April 4, 2024 10:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kcko/ac8c9075b568e4601ac701859114eb39 to your computer and use it in GitHub Desktop.
Save Kcko/ac8c9075b568e4601ac701859114eb39 to your computer and use it in GitHub Desktop.
/*
https://medium.com/just-javascript-tutorials/javascript-union-intersection-and-difference-with-es6-set-13b953b21f62
*/
const setA = new Set(['🌞', '🌝', '🌎']);
const setB = new Set(['🌎', 'πŸš€', 'πŸ‘©β€πŸš€']);
const union = new Set([...setA, ...setB]);
console.log(union); // Set(5) { '🌞', '🌝', '🌎', 'πŸš€', 'πŸ‘©β€πŸš€' }
const intersection = new Set([...setA].filter((x) => setB.has(x)));
console.log(intersection); // Set(1) { '🌎' }
const difference = new Set([...setA].filter((x) => !setB.has(x)));
console.log(difference); // Set(2) { '🌞', '🌝' }
// https://medium.com/@alvaro.saburido/set-theory-for-arrays-in-es6-eb2f20a61848
arrA=[1,3,4,5]
arrB=[1,2,5,6,7]
let intersection = arrA.filter(x => arrB.includes(x)); // [1,5]
let difference = arrA.filter(x => !arrB.includes(x)); // [3,4]
// symetrical diff [2,3,4,6,7]
let difference = arrA
.filter(x => !arrB.includes(x))
.concat(arrB.filter(x => !arrA.includes(x)));
let union = [...new Set([...arrA, ...arrB)]; // [1,2,3,4,5,6,7]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment