Last active
December 6, 2019 16:13
-
-
Save gkucmierz/8ee04544fa842411f7553ef66ac2fcf0 to your computer and use it in GitHub Desktop.
array intersection
This file contains hidden or 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
// array intersection that correctly handles also duplicates | |
const intersection = (a1, a2) => { | |
const cnt = new Map(); | |
a2.map(el => cnt.set(el, cnt.has(el) ? cnt.get(el) + 1 : 1)); | |
return a1.filter(el => cnt.has(el)).filter(el => { | |
const left = cnt.get(el); | |
if (0 < left) { | |
cnt.set(el, left - 1); | |
return true; | |
} | |
return false; | |
}); | |
}; | |
intersection('1234'.split``, '3456'.split``); // [ '3', '4' ] | |
intersection('12344'.split``, '3456'.split``); // [ '3', '4' ] | |
intersection('1234'.split``, '33456'.split``); // [ '3', '4' ] | |
intersection('12334'.split``, '33456'.split``); // [ '3', '3', '4' ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment