0

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.

user12341234
  • 1,137
  • 2
  • 10
  • 22
  • @adiga it is not a duplicate of that link. None of the answers work for more than 2 arrays or keep the index order. I tried them all. – user12341234 Oct 20 '19 at 11:25
  • At least 3 answers work with 2D arrays of any length as an input including the accepted answer. [1](https://stackoverflow.com/a/56252917/3082296), [2](https://stackoverflow.com/a/56258092/3082296), [3](https://stackoverflow.com/a/56264734/3082296) – adiga Oct 20 '19 at 11:44
  • @adiga not true, first answer only accepts 2 arrays, the other answers do not retain index order. I tested them all. – user12341234 Oct 20 '19 at 11:45
  • Please go through the answer carefully .It takes a 2D array as an input. Just use `transpose([[1,2,3],[11,22,33],[111,222,333]])` – adiga Oct 20 '19 at 11:47
  • @adiga you're correct sorry I had a typo that's why it didnt work – user12341234 Oct 20 '19 at 11:49

0 Answers0