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

How to Generate All Possible Combinations of Array Values in JavaScript?

Linda Hamilton
Linda HamiltonOriginal
2024-11-04 02:45:29277browse

How to Generate All Possible Combinations of Array Values in JavaScript?

Cartesian Product: Generating Combinations of Array Values in JavaScript

Problem Description:

Given an arbitrary number of JavaScript arrays, how do we compute the Cartesian product of their elements, effectively generating all possible combinations of their values?

Solution:

While this problem may resemble permutation, it is a classic task involving the Cartesian product. Using recursion, we can implement an algorithm to achieve this:

  1. Define an input list of arrays:

    <code class="js">var allArrays = [['a', 'b'], ['c'], ['d', 'e', 'f']];</code>
  2. Create a recursive allPossibleCases function:

    <code class="js">function allPossibleCases(arr) {
      if (arr.length === 1) {
        return arr[0];
      } else {
        var result = [];
        var allCasesOfRest = allPossibleCases(arr.slice(1)); // recur with the rest of array
        for (var i = 0; i < arr[0].length; i++) {
          for (var j = 0; j < allCasesOfRest.length; j++) {
            result.push(arr[0][i] + allCasesOfRest[j]);
          }
        }
        return result;
      }
    }</code>
  3. Instantiate the allPossibleCases function with the input list of arrays and print the results:

    console.log(allPossibleCases(allArrays));

Output:

This code will output all possible combinations of the values in the input arrays, in the following format:

["acd", "bcd", "azd", "bzd", "ace", "bce", "aze", "bze", "acf", "bcf", "azf", "bzf"]

This algorithm efficiently generates the Cartesian product of the supplied arrays, providing a solution to the problem of creating exhaustive combinations of their elements.

The above is the detailed content of How to Generate All Possible Combinations of Array Values in JavaScript?. 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