Skip to content

Instantly share code, notes, and snippets.

@souljorje
Last active October 15, 2024 06:28
Show Gist options
  • Save souljorje/9408ebddee0eb992f2e092da7cac24e6 to your computer and use it in GitHub Desktop.
Save souljorje/9408ebddee0eb992f2e092da7cac24e6 to your computer and use it in GitHub Desktop.
Combinations of multiple arrays values (cartesian product) JavaScript
const getAllCombinations = (arraysToCombine) => {
const divisors = [];
let combinationsCount = 1;
for (let i = arraysToCombine.length - 1; i >= 0; i--) {
divisors[i] = divisors[i + 1] ? divisors[i + 1] * arraysToCombine[i + 1].length : 1;
combinationsCount *= (arraysToCombine[i].length || 1);
}
const getCombination = (n, arrays, divisors) => arrays.reduce((acc, arr, i) => {
acc.push(arr[Math.floor(n / divisors[i]) % arr.length]);
return acc;
}, []);
const combinations = [];
for (let i = 0; i < combinationsCount; i++) {
combinations.push(getCombination(i, arraysToCombine, divisors));
}
return combinations;
};
getAllCombinations([['a', 'b'], ['c'], ['d', 'e']]) // [["a","c","d"],["a","c","e"],["b","c","d"],["b","c","e"]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment