简体   繁体   中英

Javascript - permutations/combinations for an undetermined number of options with undetermined numbers of values

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!

在几个月后再次返回此问题后,我在这里找到了解决问题的方法: https : //stackoverflow.com/questions/4796678/javascript-golf-cartesian-product?lq=1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM