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