# All combinations of properties in an array

Ok, I've been cheating on this thread for the last couple of days. Which is the tidiest (anything without a HUGE overhead) way to create an array of all possible combinations

``````var input = [
{a: 1}, {a: 2, b: 3},
{b: 4}, {b: 5}, {a: 6}
];
```

```

So, I want to generate the following:

``````var output = [
{a: 1}, {b: 4}, {b: 5}, {a: 6},
{a: 1, b: 4}, {a: 1, b: 5},
{a: 6, b: 4}, {a: 6, b: 5},
{a: 2, b: 3}
];
```

```

The thing is, in my particular case, I'm talking about 4 properties (and I really need to create a separate array for each set of different sets of properties, however, these are both things that I have to implement later), However, I'm only looking for some then psuedo generic code on how to approach this problem, not to someone writing this for me or something.

I feel like this should have been something I should have figured out, but I just don't get there. First, I create separate arrays for all combinations of properties (all `a`

's, all `b`

' s, all `c`

's, all `ab`

' s, all `bc`

, etc.). However, the point is that with three properties that you already have to add for each `a`

all `b`

, `c`

and `bc`

. Now writing this for a single property is easy enough, but writing a generic solution that does it for n-properties just eludes me entirely.

+3

source to share

I'm not sure I really understand the requirements, but you can try a recursive solution along these lines (in non-javascript pseudocode):

``````def generate(i,C):
# C is a dictionary representing the currently defined properties
# We are allowed to add to our set of properties from the choices input[i],input[i+1],...

while i<len(input):
if all of properties in input[i] are not in C:
Add properties in input[i] to C
solutions.append(C)
generate(i+1,C)
Remove properties in input[i] from C
i++

generate(0,{})
```

```
+3

source

All Articles