title: Finding All Combinations (Cartesian product) of JavaScript array values
body: <p>How can I produce all of the combinations of the values in N number of JavaScript arrays of variable lengths?</p>
  <p>Let's say I have N number of JavaScript arrays, e.g.</p>
  <pre><code>var first = ['a', 'b', 'c', 'd'];
  var second = ['e'];
  var third =  ['f', 'g', 'h', 'i', 'j'];
  </code></pre>
  <p>(Three arrays in this example, but its N number of arrays for the problem.)</p>
  <p>And I want to output all the combinations of their values, to produce</p>
  <pre><code>aef
  aeg
  aeh
  aei
  aej
  bef
  beg
  ....
  dej
  </code></pre>
  <hr />
  <p>EDIT: Here's the version I got working, using ffriend's accepted answer as the basis.</p>
  <pre><code>var allArrays = [['a', 'b'], ['c', 'z'], ['d', 'e', 'f']];
  
   function allPossibleCases(arr) {
    if (arr.length === 0) {
      return [];
    } 
    else if (arr.length ===1){
      return arr[0];
    }
    else {
      var result = [];
      var allCasesOfRest = allPossibleCases(arr.slice(1));  // recur with the rest of array
      for (var c in allCasesOfRest) {
        for (var i = 0; i &lt; arr[0].length; i++) {
          result.push(arr[0][i] + allCasesOfRest[c]);
        }
      }
      return result;
    }
  
  }
  var results = allPossibleCases(allArrays);
   //outputs [&quot;acd&quot;, &quot;bcd&quot;, &quot;azd&quot;, &quot;bzd&quot;, &quot;ace&quot;, &quot;bce&quot;, &quot;aze&quot;, &quot;bze&quot;, &quot;acf&quot;, &quot;bcf&quot;, &quot;azf&quot;, &quot;bzf&quot;]
  </code></pre>