Home >Web Front-end >JS Tutorial >How to Generate All Combinations of JavaScript Array Values Using Recursion?

How to Generate All Combinations of JavaScript Array Values Using Recursion?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-03 22:11:02551browse

How to Generate All Combinations of JavaScript Array Values Using Recursion?

Finding All Combinations (Cartesian Product) of JavaScript Array Values

To determine all combinations of values in a set of JavaScript arrays, we employ recursion. Unlike permutations, this process seeks to combine elements across multiple arrays rather than rearrange elements within a single array.

Here's a recursive solution that generates the Cartesian product of the given arrays:

<code class="js">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));
    for (var i = 0; i < allCasesOfRest.length; i++) {
      for (var j = 0; j < arr[0].length; j++) {
        result.push(arr[0][j] + allCasesOfRest[i]);
      }
    }
    return result;
  }
}</code>

For example, given the input arrays:

<code class="js">var first = ['a', 'b', 'c', 'd'];
var second = ['e'];
var third = ['f', 'g', 'h', 'i', 'j'];</code>

The allPossibleCases function would output the following combinations:

aef
aeg
aeh
aei
aej
bef
beg

... and so on, producing all possible combinations of elements from the three input arrays.

The above is the detailed content of How to Generate All Combinations of JavaScript Array Values Using Recursion?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn