find the cartesian product of of these sets: [1, 2, 3], ['primary', 'secondary'], ['isbold', null] in typescript

One way to find the cartesian product of multiple sets is by using nested loops. Here's how to do it in TypeScript:

index.ts
const set1 = [1, 2, 3];
const set2 = ['primary', 'secondary'];
const set3 = ['isbold', null];

const result: any[][] = [];

for (const s1 of set1) {
  for (const s2 of set2) {
    for (const s3 of set3) {
      result.push([s1, s2, s3]);
    }
  }
}

console.log(result);
272 chars
16 lines

The output of this code will be an array of arrays, where each inner array represents one combination of the sets:

index.ts
[
 [1, 'primary', 'isbold'],
 [1, 'primary', null],
 [1, 'secondary', 'isbold'],
 [1, 'secondary', null],
 [2, 'primary', 'isbold'],
 [2, 'primary', null],
 [2, 'secondary', 'isbold'],
 [2, 'secondary', null],
 [3, 'primary', 'isbold'],
 [3, 'primary', null],
 [3, 'secondary', 'isbold'],
 [3, 'secondary', null]
]
315 chars
15 lines

gistlibby LogSnag