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.
const arr = [
['one', 'blue'],
['one', 'red'],
['two', 'blue'],
['two', 'red']
];
// Based on: https://stackoverflow.com/a/59370795/1762224
const getPermutations = (list, maxLen) => {
const permute = (list, maxLen) => {
if (maxLen === 0) return [[]];
const result = [];
for (let i = 0; i < list.length; i++) {
let
copy = [...list],
head = copy.splice(i, 1),
rest = permute(copy, maxLen - 1);
for (let j = 0; j < rest.length; j++) {
result.push(structuredClone([...head, ...rest[j]]));
}
}
return result;
}
return permute(list, maxLen);
}
const permutations = getPermutations(arr, 3);
console.log(permutations);
.as-console-wrapper { top: 0; max-height: 100% !important; }
Results:
[
[ ["one", "blue"] , ["one", "red"] , ["two", "blue"] ]
[ ["one", "blue"] , ["one", "red"] , ["two", "red"] ]
[ ["one", "blue"] , ["two", "blue"] , ["one", "red"] ]
[ ["one", "blue"] , ["two", "blue"] , ["two", "red"] ]
[ ["one", "blue"] , ["two", "red"] , ["one", "red"] ]
[ ["one", "blue"] , ["two", "red"] , ["two", "blue"] ]
[ ["one", "red"] , ["one", "blue"] , ["two", "blue"] ]
[ ["one", "red"] , ["one", "blue"] , ["two", "red"] ]
[ ["one", "red"] , ["two", "blue"] , ["one", "blue"] ]
[ ["one", "red"] , ["two", "blue"] , ["two", "red"] ]
[ ["one", "red"] , ["two", "red"] , ["one", "blue"] ]
[ ["one", "red"] , ["two", "red"] , ["two", "blue"] ]
[ ["two", "blue"] , ["one", "blue"] , ["one", "red"] ]
[ ["two", "blue"] , ["one", "blue"] , ["two", "red"] ]
[ ["two", "blue"] , ["one", "red"] , ["one", "blue"] ]
[ ["two", "blue"] , ["one", "red"] , ["two", "red"] ]
[ ["two", "blue"] , ["two", "red"] , ["one", "blue"] ]
[ ["two", "blue"] , ["two", "red"] , ["one", "red"] ]
[ ["two", "red"] , ["one", "blue"] , ["one", "red"] ]
[ ["two", "red"] , ["one", "blue"] , ["two", "blue"] ]
[ ["two", "red"] , ["one", "red"] , ["one", "blue"] ]
[ ["two", "red"] , ["one", "red"] , ["two", "blue"] ]
[ ["two", "red"] , ["two", "blue"] , ["one", "blue"] ]
[ ["two", "red"] , ["two", "blue"] , ["one", "red"] ]
]