Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

union

Returns an array of distinct elements that are present in either array. Preserves order based on first appearance.

TypeScript
Copied!
1/**
2 * Returns an array of distinct elements that are present in either array.
3 * Preserves order based on first appearance.
4 *
5 * @param a - First array.
6 * @param b - Second array.
7 * @returns A new array with unique values from both arrays.
8 */
9export function union<T>(a: T[], b: T[]): T[] {
10  return Array.from(new Set([...a, ...b]));
11}
  • Concise and performant

    Uses the Set constructor for de-duplication, which provides average-case O(1) lookups — resulting in efficient merging even for large arrays.

  • Order-preserving

    Maintains the order of first appearance from both input arrays. This is useful when order is meaningful (e.g., timestamps, priorities).

  • Pure and non-mutating

    Returns a new array without altering the original inputs.

  • Works for primitive values

    Safely handles strings, numbers, booleans, and other primitive types without requiring extra logic.

  • Readable one-liner implementation

    Very compact, understandable, and easy to maintain.

Tests | Examples

TypeScript
Copied!
1test('union - with overlapping values', () => {
2  expect(union([1, 2], [2, 3])).toEqual([1, 2, 3]);
3});
4
5test('union - disjoint arrays', () => {
6  expect(union([1, 4], [2, 3])).toEqual([1, 4, 2, 3]);
7});
8
9test('union - identical arrays', () => {
10  expect(union([1, 2], [1, 2])).toEqual([1, 2]);
11});
12
13test('union - one empty array', () => {
14  expect(union([], [1, 2])).toEqual([1, 2]);
15  expect(union([1, 2], [])).toEqual([1, 2]);
16});
17
18test('union - both arrays empty', () => {
19  expect(union([], [])).toEqual([]);
20});

Common Use Cases

  • Merging datasets

    Combine two arrays of primitive values like IDs, tags, or categories into one without duplicates.

  • Client-side filtering

    Build unique filter options (e.g., all unique product types across filters).

  • Set operations

    Can be used in mathematical or logical set unions, e.g., collecting distinct roles, features, permissions.

  • Event aggregation

    Combine different sources of event identifiers or user actions while eliminating overlap.

Codebase: Utilities -> Arrays -> union | Yevhen Klymentiev