3

Pretty weird looking question, I admit.

I want to calculate the cartesian product of an array of arrays in javascript The following function (from https://stackoverflow.com/questions/4796678/javascript-golf-cartesian-product) does this for me:

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

However it needs to be called as such: product([1, 2, 3], [4], [5, 6]); # => [[1, 4, 5], [1, 4, 6], [2, 4, 5], [2, 4, 6], [3, 4, 5], [3, 4, 6]]

but what I have is an array of arrays of which the dimensions are unknown, following the above example lets say:

var arrOfArr = [[1, 2, 3], [4], [5, 6]];

How would I pass the contents of arrOfArr (as in the individual arrays) as multiple parameters to function Product while I don't know the nr of arrays in arrOfArr beforehand?

i.e: product(arrOfArr) obviously doesn't work.

Community
  • 1
  • 1
Geert-Jan
  • 18,623
  • 16
  • 75
  • 137
  • `product(arrOfArr)` would work if you did the right thing and reduced `arguments[0]` instead of `arguments`. – Robert Dec 20 '14 at 04:13

1 Answers1

3

hmm as often the case, after writing the question you know the answer ;) cartesianProductOf.apply(null,arrOfArr);

Geert-Jan
  • 18,623
  • 16
  • 75
  • 137