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