Skip to content
Advertisement

Cartesian product of multiple arrays in JavaScript

How would you implement the Cartesian product of multiple arrays in JavaScript?

As an example,

JavaScript

should return

JavaScript

Advertisement

Answer

Here is a functional solution to the problem (without any mutable variable!) using reduce and flatten, provided by underscore.js:

JavaScript
JavaScript

Remark: This solution was inspired by http://cwestblog.com/2011/05/02/cartesian-product-of-multiple-arrays/

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement