how to get all combinations of a set in javascript

To get all combinations of a set in javascript, you can use a recursive function that generates and returns an array of all possible combinations.

Here's an example implementation:

index.tsx
function getCombinations(set) {
  let combinations = [];

  function generate(current, remaining) {
    if (remaining.length === 0) {
      combinations.push(current);
    } else {
      for (let i = 0; i < remaining.length; i++) {
        generate(current.concat(remaining[i]), remaining.slice(i + 1));
      }
    }
  }

  generate([], set);
  return combinations;
}

// Example usage:
let set = [1, 2, 3];
let combinations = getCombinations(set);
console.log(combinations); // Output: [[1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
539 chars
22 lines

In this implementation, the getCombinations() function takes in a set (which is an array of unique elements) and returns an array combinations that contains all possible combinations of the set.

To generate the combinations, we use a recursive helper function generate() which takes in two arguments: current (an accumulator array that stores the current combination being generated), and remaining (the remaining elements of the set).

If there are no more remaining elements, we have generated a complete combination, so we add it to the combinations array. Otherwise, we loop through the remaining elements of the set and recursively call generate() with a new current array that includes the current element, and the remaining elements excluding the current one.

We start the recursion by calling generate() with the empty current array and the full set array.

The output of this example implementation is the array of all possible combinations of the original set.

gistlibby LogSnag