Skip to content

Instantly share code, notes, and snippets.

@FestivalBobcats
Created October 28, 2011 19:57
Show Gist options
  • Save FestivalBobcats/1323387 to your computer and use it in GitHub Desktop.
Save FestivalBobcats/1323387 to your computer and use it in GitHub Desktop.
Underscore.js implementation of Cartesian Product
function cartesianProductOf(){
return _.reduce(arguments, function(mtrx, vals){
return _.reduce(vals, function(array, val){
return array.concat(
_.map(mtrx, function(row){ return row.concat(val); })
);
}, []);
}, [[]]);
}
@dbushong
Copy link

Thanks! You should make innermost clause:

return row.concat([val]);

otherwise if someone (like me) is trying to use this on arrays of arrays, JS unwelcomely flattens the array. (And it's just as safe this way for when you're not passing arrays)

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