Intersect lists of different shapes using a per-list key
An events app wants to invite only the people who are on every team roster. The rosters come from different systems, so they do not even share a shape: one is a list of user objects, one is a plain list of email strings exported from a spreadsheet, and one nests the email inside a contact object. Emails are also cased inconsistently. Implement intersectByKey(lists, keyOf), which intersects lists by a key you derive per list.
intersectByKey(lists, keyOf) // => Array
lists: an array of arrays.keyOf(item, listIndex): returns the key of item, which belongs to lists[listIndex]. Because it receives the list index, it can read a different field from each list.Map and Set use: NaN matches NaN, 0 matches -0, and objects match only themselves.lists is empty, return []. If it holds one list, return its items without duplicate keys.keyOf can be expensive (it may normalize strings), so call it at most once per item.const design = [
{ name: 'Ivy', email: 'Ivy@acme.dev' },
{ name: 'Omar', email: 'omar@acme.dev' },
{ name: 'Lee', email: 'lee@acme.dev' },
];
const spreadsheet = ['OMAR@acme.dev', 'ivy@acme.dev', 'kim@acme.dev'];
const mobile = [{ contact: { email: 'ivy@ACME.dev' } }, { contact: { email: 'omar@acme.dev' } }];
const emailOf = (item, listIndex) => {
if (listIndex === 1) return item.toLowerCase();
if (listIndex === 2) return item.contact.email.toLowerCase();
return item.email.toLowerCase();
};
intersectByKey([design, spreadsheet, mobile], emailOf);
// => [{ name: 'Ivy', email: 'Ivy@acme.dev' }, { name: 'Omar', email: 'omar@acme.dev' }]
intersectByKey([[1.2, 2.7, 2.1, 3.9], [2.4, 3.2]], Math.floor);
// => [2.7, 3.9] (keys 2 and 3; 2.1 is a duplicate of key 2)
intersectByKey([[NaN, 0], [-0, NaN]], (n) => n);
// => [NaN, 0]
intersectByKey([['a', 'b'], []], (s) => s);
// => []