Home >Web Front-end >JS Tutorial >How to Efficiently Generate Cartesian Products from Arrays of Varying Lengths in JavaScript?
To generate all possible combinations of elements taken from a set of arrays with varying lengths, JavaScript programmers face a unique challenge. Customizing a solution to handle a dynamic number of arrays can be tricky.
A simple and efficient approach is to employ a recursive helper function like the one illustrated below:
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; }
To utilize this function, simply pass your arrays as arguments:
cartesian([0, 1], [0, 1, 2, 3], [0, 1, 2]);
The output will contain all possible combinations of elements from the provided arrays:
[ [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], ]
For an array of arrays, adjust the function's signature to function cartesian(args) instead of using rest parameters. This approach allows for handling any number of arrays with varying element counts, providing a flexible solution to this combinatorial problem.
The above is the detailed content of How to Efficiently Generate Cartesian Products from Arrays of Varying Lengths in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!