Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to generate all unique combinations of an array? [duplicate]

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?

like image 934
jkhoffman Avatar asked Aug 31 '25 21:08

jkhoffman


1 Answers

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'])));
like image 60
גלעד ברקן Avatar answered Sep 03 '25 13:09

גלעד ברקן