I'm looking for the cartesian product but I need each item to retain its index.
For example this is a cartesian product:
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([1,2,3],[11,22,33],[111,222,333])
it returns this:
[ [ 1, 11, 111 ],
[ 1, 11, 222 ],
[ 1, 11, 333 ],
[ 1, 22, 111 ],
[ 1, 22, 222 ],
[ 1, 22, 333 ],
[ 1, 33, 111 ],
[ 1, 33, 222 ],
[ 1, 33, 333 ],
[ 2, 11, 111 ],
[ 2, 11, 222 ],
[ 2, 11, 333 ],
[ 2, 22, 111 ],
[ 2, 22, 222 ],
[ 2, 22, 333 ],
[ 2, 33, 111 ],
[ 2, 33, 222 ],
[ 2, 33, 333 ],
[ 3, 11, 111 ],
[ 3, 11, 222 ],
[ 3, 11, 333 ],
[ 3, 22, 111 ],
[ 3, 22, 222 ],
[ 3, 22, 333 ],
[ 3, 33, 111 ],
[ 3, 33, 222 ],
[ 3, 33, 333 ] ]
but I need it to return this:
[
[1, 2, 3],
[1, 2, 33],
[1, 2, 333],
[1, 22, 3],
[1, 22, 33],
[1, 22, 333],
[1, 222, 3],
[1, 222, 33],
[1, 222, 333],
[11, 2, 3],
[11, 2, 33],
[11, 2, 333],
[11, 22, 3],
[11, 22, 33],
[11, 22, 333],
[11, 222, 3],
[11, 222, 33],
[11, 222, 333],
[111, 2, 3],
[111, 2, 33],
[111, 2, 333],
[111, 22, 3],
[111, 22, 33],
[111, 22, 333],
[111, 222, 3],
[111, 222, 33],
[111, 222, 333]
]
The array of arrays can be unsorted, but the arrays of numbers should be retain their indexes (in this case they are sorted but won't always be). Also if this algorithm has a name other than cartesian I would be interested in knowing.