Home > Web Front-end > JS Tutorial > How to Generate All Possible Combinations from N Arrays with M Elements Each in JavaScript?

How to Generate All Possible Combinations from N Arrays with M Elements Each in JavaScript?

Patricia Arquette
Release: 2024-11-30 16:27:11
Original
934 people have browsed it

How to Generate All Possible Combinations from N Arrays with M Elements Each in JavaScript?

Generating Combinations from N Arrays with M Elements in JavaScript [Duplicate]

Introduction
Combining elements from multiple arrays can yield numerous combinations, which are often essential in statistical analysis or combinatorial problems. This article presents a comprehensive solution in JavaScript to generate all possible combinations from N arrays, each containing M elements.

Recursive Approach
The provided solution employs a recursive helper function to construct combinations incrementally. The function iterates through each array, including its elements in the resulting combination. If the current array is the last one, the completed combination is added to the result array. Otherwise, the function recurses with the updated combination and proceeds to the next array.

Implementation

function cartesian(...args) {
    var r = [], max = args.length - 1;
    function helper(arr, i) {
        for (var j = 0, l = args[i].length; j < l; j++) {
            var a = arr.slice(0); // clone arr
            a.push(args[i][j]);
            if (i == max)
                r.push(a);
            else
                helper(a, i + 1);
        }
    }
    helper([], 0);
    return r;
}
Copy after login

Usage
To generate combinations from a list of arrays, we pass the arrays as arguments to the cartesian function.

cartesian([0, 1], [0, 1, 2, 3], [0, 1, 2]);
Copy after login

The result will be an array containing all possible combinations:

[
  [0, 0, 0],
  [0, 0, 1],
  [0, 0, 2],
  [0, 1, 0],
  [0, 1, 1],
  [0, 1, 2],
  [0, 2, 0],
  [0, 2, 1],
  [0, 2, 2],
  // ...
]
Copy after login

Note
If we prefer to pass an array of arrays instead of individual arguments, we can modify the function signature to function cartesian(args).

The above is the detailed content of How to Generate All Possible Combinations from N Arrays with M Elements Each 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