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

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

DDD
Release: 2024-11-03 16:19:02
Original
781 people have browsed it

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

Finding All Combinations (Cartesian product) of JavaScript Array Values

Producing all combinations of values from multiple arrays in JavaScript can be achieved through the concept of Cartesian product. Here's how you can approach it:

Recursion for Cartesian Product


To generate all combinations, we can use a recursive function that iterates through each array and combines elements from all arrays.

Here's an example of a recursive function that finds the Cartesian product of multiple arrays:



function allPossibleCases(arr) {<br>  if (arr.length == 1) {</p>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">return arr[0];
Copy after login

} else {

var result = [];
var allCasesOfRest = allPossibleCases(arr.slice(1)); // recur with the rest of array
for (var i = 0; i < allCasesOfRest.length; i++) {
  for (var j = 0; j < arr[0].length; j++) {
    result.push(arr[0][j] + allCasesOfRest[i]);
  }
}
return result;
Copy after login

}
}



Usage Example


Let's say you have three arrays:

var first = ['a', 'b'],<br>var second = ['c'],<br>var third =  ['d', 'e', 'f'];

Using the allPossibleCases function, you can generate all combinations as follows:




var allArrays = [first, second, third];<br>console.log(allPossibleCases(allArrays));



This will output the following combinations:

acd
ace
acf
bcd
bce
bcf
azd
aze
azf
bzd
bze
bzf
Copy after login

Note: The order of elements in each combination may vary depending on the order of arrays in the allArrays variable.

The above is the detailed content of How to Generate All Combinations (Cartesian Product) of Values from 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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template