Skip to content

Instantly share code, notes, and snippets.

@exoticknight
Last active September 26, 2018 11:46
Show Gist options
  • Save exoticknight/e134a92a8e0452aa88920610b151b465 to your computer and use it in GitHub Desktop.
Save exoticknight/e134a92a8e0452aa88920610b151b465 to your computer and use it in GitHub Desktop.
make Cartesian Product of arrays
// const arr = [
// [1,2],
// [4,5],
// [6,8]
// ]
// cartesianProduct(arr)
// [1, 4, 6]
// [2, 4, 6]
// [1, 5, 6]
// [2, 5, 6]
// [1, 4, 8]
// [2, 4, 8]
// [1, 5, 8]
// [2, 5, 8]
function cartesianProduct(a) {
return a.reduce((arr, n) => n.reduce((x, ni) => x.concat(arr.map(arri => arri.concat(ni))), []), [[]])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment