how to get the cartesian product of two sets in javascript

Here's an example function that takes two arrays as arguments and returns the cartesian product of the two sets using nested loops:

index.tsx
function cartesianProduct(setA, setB) {
  const product = [];
  
  for (let a of setA) {
    for (let b of setB) {
      product.push([a, b]);
    }
  }
  
  return product;
}
176 chars
12 lines

Here's an example usage of the function with two sets, setA and setB:

index.tsx
const setA = ['a', 'b', 'c'];
const setB = [1, 2, 3];

const product = cartesianProduct(setA, setB);
console.log(product);
// Output: [['a', 1], ['a', 2], ['a', 3], ['b', 1], ['b', 2], ['b', 3], ['c', 1], ['c', 2], ['c', 3]]
225 chars
7 lines

gistlibby LogSnag