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
});
}
}
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' ] ]
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With