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

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

Patricia Arquette
Release: 2024-11-03 17:34:30
Original
327 people have browsed it

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

Consider an example with three arrays:

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

Calling allPossibleCases(allArrays) will output:

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

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!

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