Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@ijy
Last active April 23, 2022 15:54
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • 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"]]
@hu9o
Copy link

hu9o commented Apr 28, 2016

I made a simple implementation in vanilla JS (ES6) : https://gist.github.com/hu9o/f4e80ed4b036fd76c31ef33dc5b32601

@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]))))
    )
  , [[]]);
}

@nmors
Copy link

nmors 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