Skip to content

cartesianProduct

Computes the Cartesian product of the provided arrays.

Returns all possible tuples formed by picking one element from each input array, in lexicographic order relative to the input order.

Available since v2.0.0

import { cartesianProduct } from '@helpers4/array';
cartesianProduct<T extends readonly readonly unknown[][]>(arrays: T): mapped[]
ParameterTypeDescription
arraysTTwo or more arrays to combine.

mapped[] — An array of tuples, each containing one element from each input array.

Returns all ordered pairs from two arrays.

cartesianProduct([1, 2], ['a', 'b'])
// => [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']]

Useful for generating all size/color variant combinations.

cartesianProduct(['S', 'M', 'L'], ['red', 'blue'])
// => [['S','red'],['S','blue'],['M','red'],['M','blue'],['L','red'],['L','blue']]

If any input array is empty, the result is an empty array.

cartesianProduct([1, 2], []) // => []

View source on GitHub