1

long time reader, first time writer here.

I'm trying to figure out all possible combinations of an undetermined set of javascript arrays, but can't seem to find much help.

So, if you can imagine groups of dropdowns (this is the eventual use) where there could be any number of dropdowns the user defines, and each dropdown has any number of possible values that the user also defines. (Only one value in each option can be chosen at one time.)

So as an example...

var options = [
{
    label:"Colors", 
    values:["red", "green", "blue", "etc"]
},
{
    label:"Sizes",
    values:["small", "medium", "large", "xl", "etc"]
},
{
    label:"styles",
    values:["t-shirt", "v-neck", "hoodie", "vest", "etc"]
}
//and any number of options, with any numbers of values
];

Now from there I need to generate all possible outcomes, with one value selected from each option (bonus love if the solution can have an option optional or not though, so maybe sometimes it could be set to generate all possible combinations including if only one value is selected).

So I'm hoping for a solution like

function combinations(options, option_optional){

}

with only unique combinations, then I can build a list like these

if an option is optional:

[
    ["red"],
    ["red", "large"],
    ["red", "large", "tshirt"],
    ["large"],
    ["large", "t-shirt"]

etc...

or if all options must be selected:

[
    ["red", "large", "t-shirt"],
    ["red", "medium", "t-shirt"],

etc.

I tried looking at other solutions out there but could only find ones that gave back ALL possible combinations.

Any help is appreciated and if you prefer using jquery's $.each for loops, that's fine too. Thanks in advance!

danno_blammo
  • 41
  • 1
  • 5
  • [This one](http://snippets.dzone.com/posts/show/3545) was nice, but it only worked on a one dimensional array. – danno_blammo Apr 20 '12 at 21:11
  • I've also tried http://stackoverflow.com/questions/8822950/creating-combinations-in-javascript , but I'm not smart enough to capture the solution's output into an array. – danno_blammo Apr 20 '12 at 21:58

1 Answers1

1

After returning to this problem after a couple months again, I found the answer to my problems here: https://stackoverflow.com/questions/4796678/javascript-golf-cartesian-product?lq=1

Community
  • 1
  • 1
danno_blammo
  • 41
  • 1
  • 5