Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: how to pass array-values as arguments to a function to be read using Function::arguments [duplicate]

Tags:

javascript

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.

like image 752
Geert-Jan Avatar asked Dec 29 '25 21:12

Geert-Jan


1 Answers

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

like image 118
Geert-Jan Avatar answered Dec 31 '25 09:12

Geert-Jan