1

I am facing a problem to Create a string from selected values of multiple multi-select boxes, let me explain with example below:

Suppose i have dropdown values in jQuery like the following.

country = [usa, uae, ksa, uk]
products = [animals, meat, clothes]
show-in = [value, weight]
unit= [thousands, millions, kilos, tons]

now i want to create array containing strings of all combinations, for example in above case:

all_string = 
[usa-animals-value-thousands,
usa-animals-value-millions,
usa-animals-value-kilos,
usa-animals-value-tons,
usa-animals-weight-thousands,
usa-animals-weight-millions,
usa-animals-weight-kilos,
usa-animals-weight-tons,
usa-meat-value-thousands,
usa-meat-value-millions,
.... and so on]

Please note that number of select boxs in the form are dynamic and each selectbox can have any number of values selected by user.

So far i have tried different approaches and was able to create strings to first level only, like string of each first element of every array concatenated together. But, i am not able to generate this recursively for each and every combination.

My current code is below, but this is just an idea because it did not fulfill my requirement so far.

var final_data = [];
var data = [];
jQuery('.form-filter select').each(function () {
    data.push(jQuery(this).val());
});
for (var k = 0; k < data[0].length; k++) {

    var str = "";

    for (var j = 0; j < data.length; j++) {
        str += (data[j][i] !== undefined) ? "-" + data[j][i] : ((data[j][i - 1] !== undefined) ? "-" + data[j][i - 1] : "-" + data[j][i - 2]);
    }

    final_data.push(str.slice(1));
}

Please help..

Carsten Løvbo Andersen
  • 26,637
  • 10
  • 47
  • 77
Prog_zd
  • 13
  • 5

1 Answers1

0

Okay, I found solution for my problem.

This function worked for me

function allPossibleCases(arr) {
  if (arr.length == 1) {
    return arr[0];
  } else {
    var result = [];
    var allCasesOfRest = allPossibleCases(arr.slice(1));  // recur with the rest of array
    for (var i = 0; i < allCasesOfRest.length; i++) {
      for (var j = 0; j < arr[0].length; j++) {
        result.push(arr[0][j] + allCasesOfRest[i]);
      }
    }
    return result;
  }

}

Details found here. Finding All Combinations of JavaScript array values

Community
  • 1
  • 1
Prog_zd
  • 13
  • 5