Skip to main content

union

A function that combines two arrays and returns a new array containing only unique values with duplicates removed.

By default, duplicate detection is performed only for primitive values.

If the second argument iteratee function is provided, duplicate detection is based on the iteratee return value for each element.


Code

🔗 View source code


Benchmark

  • hz: Operations per second
  • mean: Average response time (ms)

Default

NamehzmeanPerformance
modern-kit/union4,409,019.080.0002fastest
lodash/union3,714,184.110.0003slowest
  • modern-kit/union
    • 1.19x faster than lodash/union

with iteratee

NamehzmeanPerformance
modern-kit/union3,801,245.650.0003fastest
lodash/unionBy2,537,527.220.0004slowest
  • modern-kit/union
    • 1.50x faster than lodash/unionBy

Interface

typescript
function union<T>(arr1: T[] | readonly T[], arr2: T[] | readonly T[]): T[];

function union<T, U = T>(
arr1: T[] | readonly T[],
arr2: T[] | readonly T[],
iteratee?: (item: T) => U
): T[];

Usage

Basic Usage

typescript
import { union } from '@modern-kit/utils';

union([1, 2, 3, 4], [1, 2, 3, 5]); // [1, 2, 3, 4, 5]

Iteratee Usage

typescript
import { union } from '@modern-kit/utils';

const arr1 = [
{ id: 1, name: 'john' },
{ id: 2, name: 'jane' },
];
const arr2 = [
{ id: 1, name: 'john' },
{ id: 3, name: 'gromit' },
];

union(arr1, arr2, (item) => item.id);
/*
[
{ id: 1, name: 'john' },
{ id: 2, name: 'jane' },
{ id: 3, name: 'gromit' }
]
*/