Find all combinations of options in a loop

后端 未结 3 2109
孤城傲影
孤城傲影 2020-12-10 05:08

I\'m looking for the best way to loop through a bunch of options to make sure that I hit all available options.

I\'ve created a feature that allows a client to build

3条回答
  •  时光取名叫无心
    2020-12-10 05:39

    You want the Cartesian Product of all your arrays.

    I have a page discussing this, including implementations in JavaScript, on my site:
    http://phrogz.net/lazy-cartesian-product

    For example, to iterate through them all quickly in "forward" order, you can use:

    hats   = ['fez','fedora']
    shirts = ['t-shirt','long']
    pants  = ['shorts','jeans']
    shoes  = ['sneaker','loafer']
    
    lazyProduct( [hats,shirts,pants,shoes], function(hat,shirt,pant,shoe){
      // Your function is yielded unique combinations of values from the arrays
      console.log(hat,shirt,pant,shoe);
    });
    
    function lazyProduct(sets,f,context){
      if (!context) context=this;
      var p=[],max=sets.length-1,lens=[];
      for (var i=sets.length;i--;) lens[i]=sets[i].length;
      function dive(d){
        var a=sets[d], len=lens[d];
        if (d==max) for (var i=0;i

    The output:

    fez t-shirt shorts sneaker
    fez t-shirt shorts loafer
    fez t-shirt jeans sneaker
    fez t-shirt jeans loafer
    fez long shorts sneaker
    fez long shorts loafer
    fez long jeans sneaker
    fez long jeans loafer
    fedora t-shirt shorts sneaker
    fedora t-shirt shorts loafer
    fedora t-shirt jeans sneaker
    fedora t-shirt jeans loafer
    fedora long shorts sneaker
    fedora long shorts loafer
    fedora long jeans sneaker
    fedora long jeans loafer
    fez t-shirt shorts sneaker
    fez t-shirt shorts loafer
    

    This is identical to the results of:

    hats.forEach(function(hat){
      shirts.forEach(function(shirt){
        pants.forEach(function(pant){
          shoes.forEach(function(shoe){
            console.log(hat,shirt,pant,shoe);
          });
        });
      });
    });
    

    or (for older browsers):

    for (var h=0;h

    …but it supports an arbitrary number of arrays defined at runtime. (And if you're using the first "lazy" implementation from my site, you can pick out items at random, iterate in reverse, or easily stop iteration at any point.)

提交回复
热议问题