d
Amit DhamuSoftware Engineer
 

Cartesian Product

1 minute read 00000 views

The Cartesian Product mathematical equation allows us to produce a series of unique combinations based on a series of inputs.

Given we have an array of arrays as below

const sets: number[][] = [[1, 2], [3, 4, 5], [6]]

We can leverage a function like below to get us all combinations from those inputs.

const cartesianProduct = (sets: number[][]): number[][] =>
  sets.reduce<number[][]>(
    (results, ids) =>
      results
        .map(result => ids.map(id => [...result, id]))
        .reduce((nested, result) => [...nested, ...result]),
    [[]]
  )

Output

cartesianProduct(sets)

// Outputs
[
  [1, 3, 6],
  [1, 4, 6],
  [1, 5, 6],
  [2, 3, 6],
  [2, 4, 6],
  [2, 5, 6],
]