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
Release: 2024-11-04 02:45:29
Original
247 people have browsed it

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>
    Copy after login
  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>
    Copy after login
  3. Instantiate the allPossibleCases function with the input list of arrays and print the results:

    console.log(allPossibleCases(allArrays));
    Copy after login

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

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!

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