BoomerAndZiggy
BoomerAndZiggy

Reputation: 27

Passing array variables to a function generating all combinations of x number of arrays with y variables

I'm using this posted by @Bergi. It works perfectly to do the task. But I want to pass in an array variable and that's when it doesn't work. So instead of:

cartesian([0,1], [0,1,2,3], [0,1,2]); 

This instead:

var array =[[0,1], [0,1,2,3], [0,1,2]];
cartesian(array);
function cartesian() {
    var r = [], arg = arguments, max = arg.length-1;
    function helper(arr, i) {
        for (var j=0, l=arg[i].length; j<l; j++) {
            var a = arr.slice(0); // clone arr
            a.push(arg[i][j]);
            if (i==max)
                r.push(a);
            else
                helper(a, i+1);
        }
     }
    helper([], 0);
    return r;
}
cartesian([0,1], [0,1,2,3], [0,1,2]);

Really I want to do it with an array of objects and I tried that as well and got the same results which were it just returned the original three arrays. I need to do it this way because I will be passing in any number of any length arrays.

Upvotes: 1

Views: 58

Answers (1)

Paul Roub
Paul Roub

Reputation: 36438

You want .apply(), which takes an array of arguments and passes them to a function.

cartesian.apply(null, array);

function cartesian() {
  var r = [],
    arg = arguments,
    max = arg.length - 1;

  function helper(arr, i) {
    for (var j = 0, l = arg[i].length; j < l; j++) {
      var a = arr.slice(0); // clone arr
      a.push(arg[i][j]);
      if (i == max)
        r.push(a);
      else
        helper(a, i + 1);
    }
  }
  helper([], 0);
  return r;
}

var array = [
  [0, 1],
  [0, 1, 2, 3],
  [0, 1, 2]
];

var r = cartesian.apply(null, array);
console.log(r);

Upvotes: 3

Related Questions