Skip to content

Instantly share code, notes, and snippets.

@tvler
Created February 19, 2019 17:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tvler/de187999805fd0d5a7ca7c195b9538b7 to your computer and use it in GitHub Desktop.
Save tvler/de187999805fd0d5a7ca7c195b9538b7 to your computer and use it in GitHub Desktop.
Get the cartesian product of multiple sets
// Thanks to eddmann.com/posts/cartesian-product-in-javascript
const cartesianProduct = (...sets) =>
sets.reduce((sets, set) => sets.flatMap(x => set.map(y => [...x, y])), [[]]);
cartesianProduct(
['a', 'b', 'c'],
['x', 'y', 'z'],
);
// [
// ["a", "x"],
// ["a", "y"],
// ["a", "z"],
// ["b", "x"],
// ["b", "y"],
// ["b", "z"],
// ["c", "x"],
// ["c", "y"],
// ["c", "z"],
// ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment