Last active
April 4, 2024 10:32
-
-
Save Kcko/ac8c9075b568e4601ac701859114eb39 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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) { 'π', 'π' } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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