Skip to content

Instantly share code, notes, and snippets.

@leotop
Forked from ijy/cartesian-product.js
Created May 22, 2016 21:45
Show Gist options
  • Save leotop/b78c30896e8752693e6687570228856f to your computer and use it in GitHub Desktop.
Save leotop/b78c30896e8752693e6687570228856f to your computer and use it in GitHub Desktop.
Underscore.js implementation of Cartesian Product (without any mutable variable). @see: http://stackoverflow.com/questions/12303989/cartesian-product-of-multiple-arrays-in-javascript
function cartesianProductOf() {
return _.reduce(arguments, function(a, b) {
return _.flatten(_.map(a, function(x) {
return _.map(b, function(y) {
return x.concat([y]);
});
}), true);
}, [ [] ]);
};
cartesianProductOf([1, 2], [3, 4], ['a', 'b'])); // [[1,3,"a"],[1,3,"b"],[1,4,"a"],[1,4,"b"],[2,3,"a"],[2,3,"b"],[2,4,"a"],[2,4,"b"]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment