Home  >  Article  >  Web Front-end  >  How to Generate All Possible Combinations of Values in JavaScript Arrays?

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

Patricia Arquette
Patricia ArquetteOriginal
2024-11-03 17:34:30289browse

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

Finding Combinations of JavaScript Array Values

A challenge often encountered in JavaScript is finding all possible combinations of values across multiple arrays of varying lengths. This is distinct from permutations, where the order of elements matters.

To solve this problem, we employ a recursive approach:

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

Consider an example with three arrays:

<code class="javascript">var allArrays = [['a', 'b'], ['c'], ['d', 'e', 'f']];</code>

Calling allPossibleCases(allArrays) will output:

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

This method effectively combines all elements from the input arrays to generate all possible combinations, fulfilling the requirement posed in the original query.

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