# Calculate the powerset of a JavaScript array

The powerset of a set is the set of all its subsets. For example, the powerset of `[1, 2]` is `[[], [1], [2], [1, 2]]`. In order to generate the powerset of a set, we can use a simple algorithm that iterates over the elements of the set and combines them into an array containing all combinations.

For that purpose, we can use `Array.prototype.reduce()`, starting with an empty array (`[[]]`) and then combining each element with the existing combinations using `Array.prototype.map()`. For each element, we concatenate it with each existing combination and add the result to the array.

```const powerset = arr =>
arr.reduce((a, v) => a.concat(a.map(r => r.concat(v))), [[]]);

powerset([1, 2]); // [[], [1], [2], [1, 2]]```

## More like this

• Collection · 120 snippets

### Tips & Tricks

A collection of quick tips and tricks to level up your coding skills one step at a time.

• JavaScript ·

### Calculate the nth root of a number in JavaScript

Use `Math.pow()` to calculate the nth root of a given number in JavaScript.

• JavaScript ·

### Generate a JavaScript array of random integers in a given range

Combining `Math.random()` and a few simple math operations, you can generate an array of random integers in a specified range.

• JavaScript ·

### Percentile of matches

Calculates the percentage of numbers in the given array that are less or equal to the given value.

Start typing a keyphrase to see matching snippets.