For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /reference/array/cartesianProduct.md.

cartesianProduct es-toolkit

Computes the Cartesian product of the input arrays.

const tuples = cartesianProduct(arr1, arr2);

Usage

cartesianProduct(...arrs)

Use cartesianProduct when you want every possible combination of one element from each input array.

The function walks through the rightmost array first, picking each element in order. Once it has gone through every element of the rightmost array, it picks the next element from the array one position to its left and starts the rightmost array over from the beginning. This process repeats across every array, working from right to left.

import { cartesianProduct } from 'es-toolkit/array';

// Pair every number with every letter.
cartesianProduct([1, 2], ['a', 'b']);
// Returns: [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']]

// Generate all 3-bit binary tuples.
cartesianProduct([0, 1], [0, 1], [0, 1]);
// Returns: [[0,0,0], [0,0,1], [0,1,0], [0,1,1], [1,0,0], [1,0,1], [1,1,0], [1,1,1]]

If any input array is empty, the product is empty. With no arguments, the result is a single empty tuple.

import { cartesianProduct } from 'es-toolkit/array';

cartesianProduct([1, 2, 3], []); // []
cartesianProduct(); // [[]]

Parameters

arrsArray<readonly T[]>required

The arrays to take the product of.

Returns

An array of tuples representing the Cartesian product.

T[][]

Try It

::: sandpack

import { cartesianProduct } from 'es-toolkit/array';

console.log(cartesianProduct([1, 2], ['a', 'b']));

:::

Source: es-toolkit

Re-exported verbatim from es-toolkit. Implementation, edge cases, and performance behavior are owned upstream. This page mirrors the documentation at the pinned version; the linked source is authoritative.