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.

1
  • product(arrOfArr) would work if you did the right thing and reduced arguments[0] instead of arguments. Commented Dec 20, 2014 at 4:13

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.