difference
Returns items from array a
that are not present in array b
.
1/**
2 * Returns items from array 'a' that are not present in array 'b'.
3 */
4export function difference<T>(a: T[], b: T[]): T[] {
5 const setB = new Set(b);
6 return a.filter(item => !setB.has(item));
7}
Fast shallow comparison using
Set
The
Set
lookup makes the function efficient (O(n)
complexity), especially for large arrays.Preserves order from the first array
Useful for deterministic results, particularly in UI lists or ordered data.
Immutable design
Returns a new array without mutating the original input arrays.
Generic and type-safe
Uses TypeScript generics to ensure compatibility with any consistent array type (
T[]
).Simple and readable implementation
Minimal logic with clear purpose, easy to audit and extend if necessary.
Tests | Examples
1test('returns elements in array A not in array B (basic case)', () => {
2 expect(difference([1, 2, 3], [2, 4])).toEqual([1, 3]);
3});
4
5test('returns original array when B is empty', () => {
6 expect(difference([1, 2, 3], [])).toEqual([1, 2, 3]);
7});
8
9test('returns empty array when all elements of A are in B', () => {
10 expect(difference([1, 2], [1, 2, 3])).toEqual([]);
11});
12
13test('returns empty array when A is empty', () => {
14 expect(difference([], [1, 2, 3])).toEqual([]);
15});
16
17test('handles complex types (e.g., strings)', () => {
18 expect(difference(['a', 'b', 'c'], ['b'])).toEqual(['a', 'c']);
19});
20
21test('maintains order of elements in A', () => {
22 expect(difference([3, 2, 1], [2])).toEqual([3, 1]);
23});
24
25test('handles repeated values in A correctly', () => {
26 expect(difference([1, 2, 2, 3], [2])).toEqual([1, 3]);
27});
Common Use Cases
Filtering out previously processed or selected items
E.g. removing selected tags, excluding processed users, or skipping seen events.
Generating a delta between datasets
Identify what has been removed or what no longer exists between two states.
Highlighting changes in UI
Useful when comparing current state to a baseline (e.g. "items you lost access to").
Simplifying logic in access control or data sync scenarios
Quickly determine which permissions, records, or entries were removed from a newer version.