intersection
Returns a new array containing elements that exist in both input arrays. Preserves order from the first array. Supports primitive values by default.
1/**
2 * Returns a new array containing elements that exist in both input arrays.
3 * Preserves order from the first array.
4 * Supports primitive values by default.
5 *
6 * @param a - The first array.
7 * @param b - The second array.
8 * @returns A new array with shared elements between 'a' and 'b'.
9 */
10export function intersection<T>(a: T[], b: T[]): T[] {
11 const setB = new Set(b);
12 return a.filter(item => setB.has(item));
13}
Preserves order from the first array
Ensures deterministic output, useful when original sequence matters (e.g., display order or sorting logic).
Uses
Set
for efficient lookupOptimizes performance with
O(1)
average lookup time for each element from arraya
, leading to an overallO(n)
complexity.Non-mutating
Returns a new array without altering the original inputs, supporting functional programming practices.
Works generically with primitive types
Efficiently handles
string
,number
, andboolean
comparisons.Compact and readable
The implementation is clean, understandable, and easy to maintain or adapt.
Tests | Examples
1test('intersection with shared elements', () => {
2 expect(intersection([1, 2, 3], [2, 3, 4])).toEqual([2, 3]);
3});
4
5test('intersection with no common elements', () => {
6 expect(intersection([1, 2], [3, 4])).toEqual([]);
7});
8
9test('intersection with duplicates in input', () => {
10 expect(intersection([1, 2, 2, 3], [2, 3])).toEqual([2, 2, 3]);
11});
12
13test('intersection with empty second array', () => {
14 expect(intersection([1, 2, 3], [])).toEqual([]);
15});
16
17test('intersection with empty first array', () => {
18 expect(intersection([], [1, 2, 3])).toEqual([]);
19});
20
21test('intersection with different types', () => {
22 expect(intersection(['a', 'b'], ['b', 'c'])).toEqual(['b']);
23});
Common Use Cases
Filtering shared items between datasets
Useful when determining common values between user selections, tags, or IDs.
Search and filtering logic
For example, matching selected filters against available options or datasets.
Building access control lists (ACLs)
Intersecting user roles with route or resource permissions.
Data synchronization
Detecting overlapping values during list merging or when reconciling remote vs. local state.