← Back to utilities
array

difference

Creates an array of values from the first array that are not present in the other arrays. Returns a new array containing elements that exist in the first array but not in any of the subsequent arrays. The order of elements follows the order of the first array. Duplicates in the first array are preserved unless they appear in other arrays.

Installation

npx fragmen add array/difference

Source Code

/**
 * Creates an array of values from the first array that are not present in the other arrays.
 *
 * Returns a new array containing elements that exist in the first array but not in any
 * of the subsequent arrays. The order of elements follows the order of the first array.
 * Duplicates in the first array are preserved unless they appear in other arrays.
 *
 * @tags pure, array-manipulation
 * @param {T[]} array The array to inspect
 * @param {...T[][]} values Arrays of values to exclude
 * @returns {T[]} A new array of filtered values
 *
 * @example
 * ```typescript
 * const numbers = [1, 2, 3, 4, 5];
 * const toExclude = [2, 4];
 *
 * const result = difference(numbers, toExclude);
 * console.log(result); // [1, 3, 5]
 *
 * // Multiple exclusion arrays
 * const arr = [1, 2, 3, 4, 5, 6];
 * const result2 = difference(arr, [2, 3], [4, 5]);
 * console.log(result2); // [1, 6]
 *
 * // With strings
 * const words = ['apple', 'banana', 'cherry', 'date'];
 * const exclude = ['banana', 'date'];
 * const filtered = difference(words, exclude);
 * console.log(filtered); // ['apple', 'cherry']
 *
 * // No exclusions
 * difference([1, 2, 3], []); // [1, 2, 3]
 *
 * // All excluded
 * difference([1, 2, 3], [1, 2, 3]); // []
 * ```
 */
export function difference<T>(array: T[], ...values: T[][]): T[] {
  // Handle edge cases
  if (!Array.isArray(array) || array.length === 0) {
    return [];
  }

  // If no exclusion arrays provided, return copy of original
  if (values.length === 0) {
    return [...array];
  }

  // Filter out any non-array values
  const validExclusions = values.filter(arr => Array.isArray(arr));

  if (validExclusions.length === 0) {
    return [...array];
  }

  // Create a Set of all values to exclude for O(1) lookup
  const excludeSet = new Set<T>();
  for (const exclusionArray of validExclusions) {
    for (const value of exclusionArray) {
      excludeSet.add(value);
    }
  }

  // Filter array keeping only values not in exclude set
  return array.filter(item => !excludeSet.has(item));
}

Examples

const numbers = [1, 2, 3, 4, 5];
const toExclude = [2, 4];

const result = difference(numbers, toExclude);
console.log(result); // [1, 3, 5]

// Multiple exclusion arrays
const arr = [1, 2, 3, 4, 5, 6];
const result2 = difference(arr, [2, 3], [4, 5]);
console.log(result2); // [1, 6]

// With strings
const words = ['apple', 'banana', 'cherry', 'date'];
const exclude = ['banana', 'date'];
const filtered = difference(words, exclude);
console.log(filtered); // ['apple', 'cherry']

// No exclusions
difference([1, 2, 3], []); // [1, 2, 3]

// All excluded
difference([1, 2, 3], [1, 2, 3]); // []

Related Utilities

chunk

array

Splits an array into chunks of a specified size. Creates a new array containing subarrays (chunks) of the original array, each with a maximum length of the specified size. The last chunk may contain fewer elements if the array length is not evenly divisible by the chunk size.

#pure#array-manipulation

compact

array

Removes falsy values from an array. Creates a new array with all falsy values removed. Falsy values are: false, null, 0, "", undefined, and NaN. This is useful for cleaning arrays and ensuring only truthy values remain.

#pure#array-manipulation

flatten

array

Flattens nested arrays to a specified depth. Creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. A depth of 1 flattens only the first level of nesting, while Infinity flattens all levels.

#pure#array-manipulation

group-by

array

Groups the elements of an array based on the result of a callback function. Creates an object where each key represents a group and the value is an array of items that belong to that group. The grouping is determined by the callback function which is applied to each element.

#pure#array-manipulation

intersection

array

Finds the intersection of two or more arrays. Returns a new array containing only the elements that are present in all provided arrays. The order of elements in the result follows the order of the first array. Duplicates are removed from the result.

#pure#array-manipulation

sort-by

array

Sorts an array of objects by a property or using a custom function. Creates a new sorted array without mutating the original. Can sort by a property name (for objects) or by using a custom iteratee function. Supports ascending and descending order.

#pure#array-manipulation

Quick Actions

Estimated size:1.99 KB

Tags

Parameters

arrayT[]

The array to inspect

values...T[][]

Arrays of values to exclude

Returns

T[]

A new array of filtered values