Home > Web Front-end > JS Tutorial > body text

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

Patricia Arquette
Release: 2024-11-03 22:11:02
Original
494 people have browsed it

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>
Copy after login

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>
Copy after login

The allPossibleCases function would output the following combinations:

aef
aeg
aeh
aei
aej
bef
beg
Copy after login

... 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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template