Home > Web Front-end > JS Tutorial > How to Generate All Combinations (Cartesian Product) of Values in JavaScript Arrays?

How to Generate All Combinations (Cartesian Product) of Values in JavaScript Arrays?

Linda Hamilton
Release: 2024-11-03 21:05:29
Original
398 people have browsed it

How to Generate All Combinations (Cartesian Product) of Values in JavaScript Arrays?

Cartesian Product of JavaScript Array Values

Problem:

Given an arbitrary number of JavaScript arrays of varying lengths, determine all combinations (Cartesian product) of their values.

Solution:

This task can be efficiently solved using recursion. It involves iterating through each array and combining its values with all possible combinations of the remaining arrays.

Consider the following implementation:

function allPossibleCases(arr) {
  if (arr.length === 1) {
    return arr[0];
  } else {
    const result = [];
    const casesOfRest = allPossibleCases(arr.slice(1));  // recur with the rest of arr
    casesOfRest.forEach((c) => {
      for (let i = 0; i < arr[0].length; i++) {
        result.push(arr[0][i] + c);
      }
    });
    return result;
  }
}
Copy after login

Usage:

var allArrays = [['a', 'b'], ['c'], ['d', 'e', 'f']];
var results = allPossibleCases(allArrays); // outputs ["acd", "bcd", "azd", ...]
Copy after login

Explanation:

  • The allPossibleCases function takes an array of arrays as input.
  • If the input array has only one sub-array, it returns its values.
  • Otherwise, it recursively calls itself with the remaining sub-arrays and combines each sub-array value with all possible combinations of the remaining sub-arrays.
  • The function iterates through each sub-array and concatenates its values with every combination from the remaining arrays, generating all possible combinations.
  • The final result is an array of strings containing all the unique combinations of values from the input arrays.

The above is the detailed content of How to Generate All Combinations (Cartesian Product) 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