Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery/Javascript Multiple Array Combinations

I have been trying to find a solution to this with no avail. The idea of what i'm trying to achieve is to be able to find all unique combinations of multiple lists. So, let's say I have 3 lists of checkboxes (but this is an unknown number in the real-life application), Colour, Size, Pack Size. The items in the list's will be unqiue.

[0] => ['blue', 'green']
[1] => ['small', 'medium', 'large']
[2] => ['Pack Of 6', 'Pack Of 8']

I will want to get "Blue, Small, Pack Of 6", "Blue, Medium, Pack Of 6", "Blue, Large, Pack Of 6", "Blue, Small, Pack Of 8", "Blue, Medium, Pack Of 8" etc.. The ordering isn't important, but would be nice to have it logically grouped.

I already have the lists pulled out into an array using jQuery:

       options = [];

       jQuery('.option-types').each(function(){
            opts = [];
            jQuery('input:checked', this).each(function(){
                opts.push(jQuery(this).next().text());
            });
            options.push(opts)
        });

If there is a recursive functional path to answer this that would be ideal, as like i said the number of lists could be anything, aswell as the contents of the lists.

Hope you guys and girls can help, this is doing my head in.

Cheers - Dan

like image 370
dan richardson Avatar asked Oct 28 '09 10:10

dan richardson


1 Answers

This should work :)

var recursiveSearch;
var possibilities = [];

recursiveSearch = function (text, depth )
{
 text = text || "";
 depth = depth || 0;
 for ( var i = 0; i < options[depth].length; i++ )
 {
   // is there one more layer?
   if ( depth +1 < options.length )
     // yes: iterate the layer
     recursiveSearch ( text + ((text=="") ? "" : " ") + options[depth][i] , depth +1 );
   else
     // no: this is the last layer. we add the result to the array
     possibilities.push ( text + options[depth][i] );
 }
}


recursiveSearch ( );

with your array

[0] => ['blue', 'green']
[1] => ['small', 'medium', 'large']
[2] => ['Pack Of 6', 'Pack Of 8']

the result would be sth like this:

  1. blue small pack of 6
  2. blue small pack of 8
  3. blue medium pack of 6
  4. ...
like image 148
jantimon Avatar answered Sep 20 '22 14:09

jantimon