I have a collection of objects and I am in search of various combinations for them. The code I currently have is able to find all the combinations, but it only calculates the number of combinations based on the length of the input array.
For instance, using the provided array with the function below results in 27 potential combinations. However, these combinations do not include single elements or pairs.
[
[{ optionName: "red" },{ optionName: "blue" },{ optionName: "green" }],
[{ optionName: "S" },{ optionName: "L" },{ optionName: "XL" }],
[{ optionName: "spotted" },{ optionName: "striped" },{ optionName: "lined" }],
]
Here are some examples of the combinations:
[{ optionName: "red" },{ optionName: "L" },{ optionName: "spotted" }]
[{ optionName: "red" },{ optionName: "S" },{ optionName: "spotted" }]
[{ optionName: "red" },{ optionName: "S" },{ optionName: "lined" }]
However, I also want to generate combinations like:
[{ optionName: "red" }]
[{ optionName: "red" },{ optionName: "S" }]
[{ optionName: "red" },{ optionName: "L" }]
This is the current code implementation:
var r = [],
arg = arrayOfObjects,
max = arg.length - 1;
function helper(arr, i) {
for (var j = 0, l = arg[i].length; j < l; j++) {
var a = arr.slice(0);
a.push(arg[i][j]);
if (i == max) r.push(a);
else helper(a, i + 1);
}
}
helper([], 0);
Is there a way to identify all combinations, including individual and paired options?