I have an array of 16 arrays like this:
[['one', 'blue'], ['one', 'red'], ['two', 'blue'], ['two', 'red'], ...]
and I’m looking for Javascript to return every combination (not permutation, because I don’t want repeats in different orders) of THREE of them like this:
[[['one', 'blue'], ['one', 'red'], ['two', 'blue']],
[['one', 'blue'], ['one', 'red'], ['two', 'red']],
[['one', 'blue'], ['two', 'blue'], ['two', 'red']],
[['one', 'red'], ['two', 'blue'], ['two', 'red']], ...]
I can do this in Python using itertools, but I don’t know how to in Javascript.
Thanks!
2
Answers
You could use three nested for loops.
Or, if you need a shallow copy instead of references:
You want to generate a list of permutations of a fixed length.
There are many algorithms out there for recursively building a list of permutations.
I modified one that was easy to find, with proper searching. I called
stucturedClone
to grab a deep copy of each result item.Results: