how to get all subsets of a set in javascript

You can use a recursive approach to get all subsets of a set a in JavaScript. Here's one way to do it:

index.tsx
function getSubsets(a) {
  // base case
  if (a.length === 0) {
    return [[]];
  }
  
  // get all subsets without the last element
  const subsets = getSubsets(a.slice(0, -1));

  // add the last element to each subset
  const lastElement = a.slice(-1);
  return subsets.concat(subsets.map(subset => [...subset, lastElement]));
}

const set = [1, 2, 3];
const allSubsets = getSubsets(set);
console.log(allSubsets); // [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]
476 chars
18 lines

In this approach, we first define a base case for an empty set, which returns an array containing the empty set. For non-empty sets, we get all subsets without the last element using recursion. Then, for each of these subsets, we add the last element to create new subsets. Finally, we combine the original subsets with the new subsets to get all possible subsets of the original set.

gistlibby LogSnag