1

I'm trying to make a Cartesian product between sub-arrays of a 2D array. My 2dArray is for ex like this: var matrix = [[1,2,3], [4,5], [6,7,8],[9,10,11]];, but it can have variable number of arrays.

The function that i use is:

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

I tried to use the function like: cartesianProductOf(matrix) but this does not return any result.

My problem is how to give sub-arrays as parameter for this function? How to split the 2d array in sub-arrays or how to modify the function to work for my case?

Does anyone know how to solve this problem?

Update: http://jsfiddle.net/XHEJt/10/

var matrix = [[1,2,3], [4,5], [6,7,8],[9,10,11]];

console.log(cartesianProductOf([1,2,3], [4,5], [6,7,8],[9,10,11]));


//the following line does not produce the same output

console.log(cartesianProductOf(matrix));


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;
  }, [[]]);
}
HelenA
  • 96
  • 1
  • 11

1 Answers1

0

While you are asking about a function call with parameters (which works) and with an array (which does not work), you could insert a check, if arguments.length is equal to one, and then take the first element of arguments as value for reducing.

return Array.prototype.reduce.call(arguments.length === 1
    ? arguments[0]
    : arguments, function(a, b) {
        // ...
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392