Cartesian Product of Multiple Arrays

A few weeks ago, I came across a question about finding the cartesian product of two or more arrays in JavaScript. For anybody who is looking to do so, I posted the following code on stackoverflow:

function cartesianProductOf() {
  return Array.prototype.reduce.call(arguments, function(a, b) {
    var ret = [];
    a.forEach(function(a) {
      b.forEach(function(b) {
        ret.push(a.concat([b]));
      });
    });
    return ret;
  }, [[]]);
}

It is important to note that the above code will only work on newer browsers that implement Array.prototype.forEach() and Array.prototype.reduce(). If you must allow this function to be used on any browser or even in a stand-alone Windows Host Script, I would suggest using this version of jPaq which implements the functions if they aren’t already present. As of yet, I have not received any requests to see this in a JavaScript library. If you do want it in a library, let me know of your suggestions for a better name than cartesianProductOf. My issue with the name is that it is too long.

7 Replies to “Cartesian Product of Multiple Arrays”

  1. Found your site on yahoo today and really liked it.. I bookmarked it and will be back to check it out some more later.

  2. Thanks for sharing this nice piece of code.

    I am suggesting the following improvement (using reduce, map and flatten from underscore) that is more functional-like because it doesn’t use mutable variables:

    function cartesianProductOf() {
    return _.reduce(arguments, function(a, b) {
    return _.flatten(_.map(a, function(x) {
    return _.map(b, function(y) {
    return x.concat([y]);
    });
    }), true);
    }, [ [] ]);
    };

    Look at it here: http://stackoverflow.com/a/12628791/813665

Leave a Reply

Your email address will not be published. Required fields are marked *