Search code examples
javascriptsubsetpowerset

How to find all subsets of a set in JavaScript? (Powerset of array)


I need to get all possible subsets of an array.

Say I have this:

[1, 2, 3]

How do I get this?

[], [1], [2], [3], [1, 2], [2, 3], [1, 3], [1, 2, 3]

I am interested in all subsets. For subsets of specific length, refer to the following questions:

  • Finding subsets of size n: 1, 2
  • Finding subsets of size > 1: 1

Solution

  • Here is one more very elegant solution with no loops or recursion, only using the map and reduce array native functions.

    const getAllSubsets = 
          theArray => theArray.reduce(
            (subsets, value) => subsets.concat(
             subsets.map(set => [value,...set])
            ),
            [[]]
          );
    
    console.log(getAllSubsets([1,2,3]));