← Back to utilities
array

intersection

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.

Installation

npx fragmen add array/intersection

Source Code

/**
 * 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.
 *
 * @tags pure, array-manipulation
 * @param {T[][]} arrays The arrays to find intersection of
 * @returns {T[]} A new array containing elements common to all input arrays
 *
 * @example
 * ```typescript
 * const arr1 = [1, 2, 3, 4];
 * const arr2 = [2, 3, 4, 5];
 * const arr3 = [3, 4, 5, 6];
 *
 * const common = intersection(arr1, arr2);
 * console.log(common); // [2, 3, 4]
 *
 * const commonAll = intersection(arr1, arr2, arr3);
 * console.log(commonAll); // [3, 4]
 *
 * // With strings
 * const words1 = ['apple', 'banana', 'cherry'];
 * const words2 = ['banana', 'cherry', 'date'];
 * const commonWords = intersection(words1, words2);
 * console.log(commonWords); // ['banana', 'cherry']
 *
 * // No intersection
 * const noCommon = intersection([1, 2], [3, 4]);
 * console.log(noCommon); // []
 *
 * // With duplicates
 * const dup1 = [1, 1, 2, 3];
 * const dup2 = [1, 2, 2, 4];
 * const uniqueCommon = intersection(dup1, dup2);
 * console.log(uniqueCommon); // [1, 2]
 * ```
 */
export function intersection<T>(...arrays: T[][]): T[] {
  // Handle edge cases
  if (arrays.length === 0) {
    return [];
  }

  // If any input is not an array, return empty (no intersection possible)
  if (arrays.some(arr => !Array.isArray(arr))) {
    return [];
  }

  if (arrays.length === 1) {
    return [...new Set(arrays[0])];
  }

  // Use the first array as the base and check against others
  const [first, ...rest] = arrays;

  // Create sets for all other arrays for efficient lookup
  const otherSets = rest.map(arr => new Set(arr));

  // Filter first array elements that exist in all other arrays
  const result: T[] = [];
  const seen = new Set<T>();

  for (const item of first) {
    if (!seen.has(item) && otherSets.every(set => set.has(item))) {
      result.push(item);
      seen.add(item);
    }
  }

  return result;
}

Examples

const arr1 = [1, 2, 3, 4];
const arr2 = [2, 3, 4, 5];
const arr3 = [3, 4, 5, 6];

const common = intersection(arr1, arr2);
console.log(common); // [2, 3, 4]

const commonAll = intersection(arr1, arr2, arr3);
console.log(commonAll); // [3, 4]

// With strings
const words1 = ['apple', 'banana', 'cherry'];
const words2 = ['banana', 'cherry', 'date'];
const commonWords = intersection(words1, words2);
console.log(commonWords); // ['banana', 'cherry']

// No intersection
const noCommon = intersection([1, 2], [3, 4]);
console.log(noCommon); // []

// With duplicates
const dup1 = [1, 1, 2, 3];
const dup2 = [1, 2, 2, 4];
const uniqueCommon = intersection(dup1, dup2);
console.log(uniqueCommon); // [1, 2]

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

difference

array

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.

#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

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:2.06 KB

Tags

Parameters

arraysT[][]

The arrays to find intersection of

Returns

T[]

A new array containing elements common to all input arrays