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

removeValuesDeep

Removes deeply equal values from an array.

Note: This utility uses another utility: deepEqual
TypeScript
Copied!
1/**
2 * Removes deeply equal values from an array.
3 *
4 * @param arr - The input array.
5 * @param valuesToRemove - One or more values to be removed based on deep equality.
6 * @returns A new array without the deeply equal values.
7 */
8export function removeValuesDeep<T>(arr: T[], ...valuesToRemove: T[]): T[] {
9  return arr.filter(item => !valuesToRemove.some(val => deepEqual(item, val)));
10}
  • Supports deep equality checks

    Unlike shallow comparisons (===), this utility uses structural comparison (deepEqual) to detect and remove values that are logically equivalent, even if they are different object references.

  • Flexible removal

    Accepts multiple values to remove via rest parameters, providing a convenient and concise interface.

  • Non-mutating behavior

    Returns a new array, preserving immutability principles and making the function safe for use in functional programming pipelines.

Tests | Examples

TypeScript
Copied!
1test('removeValuesDeep removes deeply equal objects and arrays', () => {
2  const data = [{ a: 1 }, { a: 2 }, { a: 1 }];
3  expect(removeValuesDeep(data, { a: 1 })).toEqual([{ a: 2 }]);
4
5  const nested = [[1, 2], [3, 4], [1, 2]];
6  expect(removeValuesDeep(nested, [1, 2])).toEqual([[3, 4]]);
7});
8
9test('removeValuesDeep handles primitive values', () => {
10  expect(removeValuesDeep([1, 2, 3], 2)).toEqual([1, 3]);
11});
12
13test('removeValuesDeep works with mixed types', () => {
14  const values = [1, { x: [10, 20] }, 'hello', [1, 2]];
15  expect(removeValuesDeep(values, { x: [10, 20] }, [1, 2])).toEqual([1, 'hello']);
16});

Common Use Cases

  • Cleaning data with nested structures

    Ideal for removing unwanted or duplicate entries in arrays of objects, particularly in backend APIs or frontend state management scenarios.

  • Selective filtering of object lists

    Useful when comparing entities like { id: 1, name: "Alice" } even if their reference differs but structure matches (e.g., after a fetch or merge operation).

  • Content moderation and filtering

    Helps remove sensitive or blacklisted data structures that might not be identical by reference but share the same content.

  • Custom difference logic

    Can act as a more flexible alternative to shallow difference() utilities when working with JSON-like or deeply nested datasets.

  • Form data sanitation

    Useful in UI components where previously submitted complex data must be excluded from a new list.

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