Last active
October 15, 2024 06:28
-
-
Save souljorje/9408ebddee0eb992f2e092da7cac24e6 to your computer and use it in GitHub Desktop.
Combinations of multiple arrays values (cartesian product) JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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