Function unionBy

  • Creates an array of unique values, in order, from all given arrays using a provided mapping function to determine equality.

    Type Parameters

    • T

      The type of elements in the array.

    • U

      The type of mapped elements.

    Parameters

    • arr1: readonly T[]

      The first array.

    • arr2: readonly T[]

      The second array.

    • mapper: ((item: T) => U)

      The function to map array elements to comparison values.

        • (item): U
        • Parameters

          • item: T

          Returns U

    Returns T[]

    A new array containing the union of unique elements from arr1 and arr2, based on the values returned by the mapping function.

    // Custom mapping function for numbers (modulo comparison)
    const moduloMapper = (x) => x % 3;
    unionBy([1, 2, 3], [4, 5, 6], moduloMapper);
    // Returns [1, 2, 3]
    // Custom mapping function for objects with an 'id' property
    const idMapper = (obj) => obj.id;
    unionBy([{ id: 1 }, { id: 2 }], [{ id: 2 }, { id: 3 }], idMapper);
    // Returns [{ id: 1 }, { id: 2 }, { id: 3 }]