Skip to content

Instantly share code, notes, and snippets.

@ijy
Last active April 23, 2022 15:54
Show Gist options
  • Save ijy/6094414 to your computer and use it in GitHub Desktop.
Save ijy/6094414 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"]]
@eschwartz
Copy link

function cartesianProduct(var_sets) {
  const args = [].slice.call(arguments, 0);

  return args.reduce((a, b)=> (
    _.flatten(
      a.map(x => b.map(y => x.concat([y]))))
    )
  , [[]]);
}

@pickworth
Copy link

pickworth commented Jul 19, 2018

You don't need to use arguments, slice, or call, if you use a rest parameter:

const xProd = (...args) => args.reduce((a, b) => (
    _.flatten(
      a.map(x => b.map(y => x.concat([y]))))
    )
  , [[]]
)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment