Javascript Cartesian Product

Date: 2020-03-05

(Returns all combinations for one or more arrays)

function* cartesian(arrays) {
	let remainder = arrays.length > 1 ? cartesian(arrays.slice(1)) : [[]];
	for (let r of remainder)
		for (let h of arrays[0])
			yield [h, ...r];
}

const data = Array.from(cartesian([
	['A', 'B', 'C'],
	[1, 2, 3, 4],
	['I', 'II']
]));

console.log(data);
data.sort();
console.log(data);

In Typescript

function* cartesian<T>(arrays: T[][]): Generator<T[]> {
  const remainder = arrays.length > 1 ? cartesian(arrays.slice(1)) : [[]];
  for (let r of remainder) {
    for (let h of arrays[0]) {
      yield [h, ...r];
    }
  }
}

Output:

[ [ 'A', 1, 'I' ],
  [ 'B', 1, 'I' ],
  [ 'C', 1, 'I' ],
  [ 'A', 2, 'I' ],
  [ 'B', 2, 'I' ],
  [ 'C', 2, 'I' ],
  [ 'A', 3, 'I' ],
  [ 'B', 3, 'I' ],
  [ 'C', 3, 'I' ],
  [ 'A', 4, 'I' ],
  [ 'B', 4, 'I' ],
  [ 'C', 4, 'I' ],
  [ 'A', 1, 'II' ],
  [ 'B', 1, 'II' ],
  [ 'C', 1, 'II' ],
  [ 'A', 2, 'II' ],
  [ 'B', 2, 'II' ],
  [ 'C', 2, 'II' ],
  [ 'A', 3, 'II' ],
  [ 'B', 3, 'II' ],
  [ 'C', 3, 'II' ],
  [ 'A', 4, 'II' ],
  [ 'B', 4, 'II' ],
  [ 'C', 4, 'II' ] ]

[ [ 'A', 1, 'I' ],
  [ 'A', 1, 'II' ],
  [ 'A', 2, 'I' ],
  [ 'A', 2, 'II' ],
  [ 'A', 3, 'I' ],
  [ 'A', 3, 'II' ],
  [ 'A', 4, 'I' ],
  [ 'A', 4, 'II' ],
  [ 'B', 1, 'I' ],
  [ 'B', 1, 'II' ],
  [ 'B', 2, 'I' ],
  [ 'B', 2, 'II' ],
  [ 'B', 3, 'I' ],
  [ 'B', 3, 'II' ],
  [ 'B', 4, 'I' ],
  [ 'B', 4, 'II' ],
  [ 'C', 1, 'I' ],
  [ 'C', 1, 'II' ],
  [ 'C', 2, 'I' ],
  [ 'C', 2, 'II' ],
  [ 'C', 3, 'I' ],
  [ 'C', 3, 'II' ],
  [ 'C', 4, 'I' ],
  [ 'C', 4, 'II' ] ]

35680cookie-checkJavascript Cartesian Product