Intersection ByLoading saved progress…

Intersection By

Implement intersectionBy(...arrays, iteratee) — return the elements of the first array that also appear in every other array, where two elements count as the same when they produce the same value under iteratee. Picture comparing guest lists from several parties not by the exact name strings but by some derived key — last name, or membership ID — and reporting who showed up to all of them. This mirrors Lodash's _.intersectionBy: the last argument is the iteratee — a function called on each element, or a property-name string as shorthand for "compare by this field."

Signature

// ...arrays: T[][]              — one or more arrays. The FIRST one drives the
//                                 result; the rest are membership filters.
// iteratee:  ((el: T) => U)     — the LAST argument: a function returning the
//          | string             — comparison key, OR a property name (shorthand
//                                 for el => el[name]). If omitted (the last arg
//                                 is itself an array), it defaults to identity.
// returns:   T[]
//   The elements OF THE FIRST array whose mapped key appears in every other
//   array, de-duplicated by mapped key, in first-array order.
function intersectionBy(...arrays, iteratee): T[];

Examples

// Function iteratee: compare by integer part.
// 2.1 floors to 2, which [2.3, 3.4] also produces; 1.2 floors to 1, which it does not.
intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor);
// → [2.1]   (the original 2.1, not the key 2 and not 2.3)
// Property-name iteratee: compare objects by their `x` field.
intersectionBy([{ x: 1 }, { x: 2 }], [{ x: 2 }, { x: 3 }], 'x');
// → [{ x: 2 }]

Notes

  • The last argument is the iteratee. A function is called on each element to get its comparison key; a string is a property name, so intersectionBy(a, b, 'id') compares by el.id. If the last argument is an array, no iteratee was passed — default it to identity (v => v).
  • Result comes from the first array. You return the original first-array elements, never their mapped keys and never elements from the other arrays. For objects, that means referential identity: the returned object is the exact one from the first array.
  • "In every other array" is an AND. With three or more arrays, an element survives only if its key is present in all the others. Missing from even one drops it.
  • De-duplicate by mapped key. If two first-array elements share a key, only the first occurrence can appear in the result. [2.1, 2.5] both floor to 2; at most 2.1 survives.
  • Order is first-array order. Surviving elements keep the order they had in the first array — not sorted, not the other arrays' order.
  • Empty in, empty out. An empty first array returns []. If any other array is empty, nothing can be present in all of them, so the result is [] too.
  • Don't mutate the inputs. Read every array; build a fresh result.
Loading editor…