Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cartesian product of 2 arrays

I have 2 arrays that I want a Cartesian product of. As an example:

Customer Array:

[10,A]
[11,B]

Debtor Array:

[88,W]
[99,X]

I want to produce a new customerDebtor array with:

[10,A,88,W]
[10,A,99,X]
[11,B,88,W]
[11,B,99,X]

I am attempting it with this code:

for (var i = 0; i < customerArray.length; i++) {
    for (var l = 0; l < debtorArray.length; l++) {
        $.each(customerArray[i], function (ndx, val) {
            //???? push values into customerDebtorMatrix array
        });
    }
}
like image 437
Greg Avatar asked Sep 29 '13 17:09

Greg


2 Answers

You don't need jquery for this:

var customerArray = [[10,'A'],[11,'B']];
var debtorArray = [[88,'W'],[99,'X']];

var customerDebtorMatrix = [];
for (var i = 0; i < customerArray.length; i++) {
    for (var l = 0; l < debtorArray.length; l++) {
        customerDebtorMatrix.push(customerArray[i].concat(debtorArray[l]));
    }
}

customerDebtorMatrix will be

[ [ 10, 'A', 88, 'W' ],
  [ 10, 'A', 99, 'X' ],
  [ 11, 'B', 88, 'W' ],
  [ 11, 'B', 99, 'X' ] ]
like image 126
SheetJS Avatar answered Oct 02 '22 23:10

SheetJS


concatMap works well here:

(function() {
    'use strict';

    // cartProd :: [a] -> [b] -> [[a, b]]
    function cartProd(xs, ys) {
        return [].concat.apply([], xs.map(function (x) {
            return [].concat.apply([], ys.map(function (y) {
                return [[x, y]];
            }));
        }));
    }

    return cartProd(["alpha", "beta", "gamma"], [1, 2, 3]);

})(); 

Returning:

[["alpha", 1], ["alpha", 2], ["alpha", 3], ["beta", 1], ["beta", 2], ["beta", 3], ["gamma", 1], ["gamma", 2], ["gamma", 3]]
like image 43
user6026368 Avatar answered Oct 03 '22 00:10

user6026368