Created
February 19, 2019 17:49
-
-
Save tvler/de187999805fd0d5a7ca7c195b9538b7 to your computer and use it in GitHub Desktop.
Get the cartesian product of multiple sets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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