Last active
April 23, 2022 15:54
-
-
Save ijy/6094414 to your computer and use it in GitHub Desktop.
Underscore.js implementation of Cartesian Product (without any mutable variable).
@see: http://stackoverflow.com/questions/12303989/cartesian-product-of-multiple-arrays-in-javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function cartesianProductOf() { | |
return _.reduce(arguments, function(a, b) { | |
return _.flatten(_.map(a, function(x) { | |
return _.map(b, function(y) { | |
return x.concat([y]); | |
}); | |
}), true); | |
}, [ [] ]); | |
}; | |
cartesianProductOf([1, 2], [3, 4], ['a', 'b'])); // [[1,3,"a"],[1,3,"b"],[1,4,"a"],[1,4,"b"],[2,3,"a"],[2,3,"b"],[2,4,"a"],[2,4,"b"]] |
eschwartz
commented
Oct 4, 2016
You don't need to use arguments, slice, or call, if you use a rest parameter:
const xProd = (...args) => args.reduce((a, b) => (
_.flatten(
a.map(x => b.map(y => x.concat([y]))))
)
, [[]]
)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment