Assume I have this array:
const input = [“a”, “b”, “c”, “d”];
I want to create this output:
[
[“a”],
[“a”, “b”],
[“a”, “c”],
[“a”, “d”],
[“a”, “b”, “c”],
[“a”, “b”, “d”],
[“a”, “c”, “d”],
[“a”, “b”, “c”, “d”],
[“b”],
[“b”, “c”],
[“b”, “d”],
[“b”, “c”, “d”],
[“c”],
[“c”, “d”],
[“d”]
]
I don’t care about the order, or the length of the combos, just need all the various ways to uniquely combine the items in the array.
What is the best way to do this in JavaScript? I suspect there’s a beautiful recursive solution, but iterative would work too.
Also, what is the correct technical term for this?
The correct technical term is power set. Here is the canonical recursive form:
const f = (A, i=0) => i == A.length ? [[]] : f(A, i+1).flatMap(x => [x, [A[i]].concat(x)]);
console.log(JSON.stringify(f(['a', 'b', 'c', 'd'])));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With