Return items present in every array using a custom comparator
Two records often describe the same thing without being === equal: the same user with a differently cased email, the same price within a rounding tolerance, the same product fetched twice from an API. Implement commonItems(arrays, isSame), which returns the items that appear in every array, where “appears” is decided by a comparator you are given.
commonItems(arrays, isSame) // => Array
arrays: an array of arrays.isSame(a, b): returns true when a and b count as the same item.b of that array makes isSame(item, b) return true. Always pass the item from the first array as the first argument.isSame(kept, item) is true for an item kept that is already in the result.isSame. Do not use ===, includes, or a Set to compare items.arrays is empty, return []. If it holds a single array, return a new array with that array’s items, without duplicates.const sameEmail = (a, b) => a.email.toLowerCase() === b.email.toLowerCase();
commonItems(
[
[{ email: 'Ivy@mail.dev', team: 'web' }, { email: 'omar@mail.dev', team: 'web' }],
[{ email: 'ivy@mail.dev', team: 'ios' }, { email: 'lee@mail.dev' }],
[{ email: 'IVY@MAIL.DEV' }, { email: 'omar@mail.dev' }],
],
sameEmail,
);
// => [{ email: 'Ivy@mail.dev', team: 'web' }] (the object from the first array)
const close = (a, b) => Math.abs(a - b) < 0.1;
commonItems([[1, 2.5, 4], [2.49, 3.95], [4.05, 2.52]], close);
// => [2.5, 4]
const sameLetter = (a, b) => a.toLowerCase() === b.toLowerCase();
commonItems([['q', 'Q', 'r', 'q']], sameLetter);
// => ['q', 'r']
commonItems([[1, 2], []], (a, b) => a === b);
// => []