Home >Web Front-end >JS Tutorial >How to Generate All Combinations from Multiple Arrays in JavaScript?

How to Generate All Combinations from Multiple Arrays in JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-12-01 14:03:11548browse

How to Generate All Combinations from Multiple Arrays in JavaScript?

Generating Combinations from Multiple Arrays in JavaScript

In JavaScript, generating combinations from arrays of varying sizes can be a complex task. Let's explore a solution using a recursive helper function.

Solution

The cartesian function takes an arbitrary number of arrays as parameters and returns an array of all possible combinations. It utilizes a recursive helper function, helper, which iterates through each element in an array and pushes it to a cloned version of the current combination. If the current array is not the last one, it recursively calls helper to generate all combinations for the remaining arrays.

The cartesian function can be used as follows:

cartesian([0,1], [0,1,2,3], [0,1,2]);

This will produce the desired 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]

Usage

To use this solution with an array of arrays, simply pass the array as a single parameter to the cartesian function. The helper function will automatically iterate through the nested arrays to generate all possible combinations.

Example

var data = [[0,1], [0,1,2,3], [0,1,2]];
var combinations = cartesian(data);

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