Skip to content

Instantly share code, notes, and snippets.

@gkucmierz
Last active December 6, 2019 16:13
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 gkucmierz/8ee04544fa842411f7553ef66ac2fcf0 to your computer and use it in GitHub Desktop.
Save gkucmierz/8ee04544fa842411f7553ef66ac2fcf0 to your computer and use it in GitHub Desktop.
array intersection
// 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