Union ByLoading saved progress…

Union By

Implement unionBy(...arrays, iteratee) — concatenate every input array and return the unique values in order of first appearance, where two elements count as the same when they produce the same value under iteratee. Picture merging several mailing lists into one with no repeats, but deciding "repeat" by a derived key — an email address, a normalized name — rather than by exact object equality. This mirrors Lodash's _.unionBy: the last argument is the iteratee — a function called on each element, or a property-name string as shorthand for "dedupe by this field."

Signature

// ...arrays: T[][]              — one or more arrays, read left to right and
//                                 flattened into a single stream of elements.
// iteratee:  ((el: T) => U)     — the LAST argument: a function returning the
//          | string             — identity 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[]
//   A NEW array of the unique elements across all inputs, in first-appearance
//   order. The FIRST element to produce a given key wins; later elements with
//   the same key are dropped.
function unionBy(...arrays, iteratee): T[];

Examples

// Function iteratee: dedupe by integer part.
// 2.1 floors to 2 (kept first); 1.2 floors to 1 (new); 2.3 floors to 2 (already taken).
unionBy([2.1], [1.2, 2.3], Math.floor);
// → [2.1, 1.2]   (the original 2.1, not the key 2 and not 2.3)
// Property-name iteratee: dedupe objects by their `x` field.
unionBy([{ x: 1 }], [{ x: 2 }, { x: 1 }], 'x');
// → [{ x: 1 }, { x: 2 }]   (the second { x: 1 } collides and is dropped)

Notes

  • The last argument is the iteratee. A function is called on each element to get its identity key; a string is a property name, so unionBy(a, b, 'id') dedupes by el.id. If the last argument is an array, no iteratee was passed — default it to identity (v => v).
  • First occurrence wins. When several elements map to the same key, only the first one encountered survives — and it survives as the original element. For objects that means referential identity: the returned object is the exact one you passed in.
  • De-dupe across AND within arrays. A key seen in an earlier array suppresses it in a later one, and a repeat inside a single array is suppressed too. There's one running set of seen keys for the whole flattened stream.
  • Order is first-appearance. Survivors keep the order in which their key was first seen across all arrays — not sorted, not grouped by array.
  • Empty arrays just contribute nothing. An empty array among the inputs adds no elements; all-empty (or no arrays at all) returns [].
  • Don't mutate the inputs. Read every array; build a fresh result.
Loading editor…