Skip to content

Instantly share code, notes, and snippets.

@sam-roth
Created September 22, 2016 00:07
Show Gist options
  • Save sam-roth/3a0a89750c58ece4c24ecfb69db701b9 to your computer and use it in GitHub Desktop.
Save sam-roth/3a0a89750c58ece4c24ecfb69db701b9 to your computer and use it in GitHub Desktop.
Google Sheets Function for Cartesian Products
// Usually, you'll want to transpose the input (`CARTESIAN_PRODUCT(TRANSPOSE(X1:Y2))`)
function CARTESIAN_PRODUCT(args) {
if (args.length === 0) {
return [];
}
var first = args[0].filter(function (x) { return x; });
if (args.length === 1) {
return first;
}
var rest = args.slice(1);
var restProduct = CARTESIAN_PRODUCT(rest);
var result = [];
first.forEach(function (f) {
restProduct.forEach(function (r) {
result.push([f].concat(r));
});
});
return result;
}
@DiesIrae
Copy link

Thanks for the formula! I replaced return x with return x !== "" in the filter in order to keep explicitely declared falsy values, like "0" or "FALSE"
https://gist.github.com/DiesIrae/7ea457d6c81a119f656cd5384ceaea84

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment