user3201500
user3201500

Reputation: 1618

Create all the combinations of an array with multiple sub array in Javascript

I am trying to create multiple array with combination.

here is how my array looks like:

var a1 = ["1", "2", "3"];
        var a2 = ["a", "b"];
        var a3 = ["q", "w", "e"];

        var a4 = [a1, a2, a3];

I have tried one code which looks like this:

function allPossibleCases(a4) {
              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++) {
                    // console.log(arr[0][j]);
                    // console.log(allCasesOfRest[i]);
                    result.push(arr[0][j] + allCasesOfRest[i]);
                  }

                }
                return result;
              }

        }

Which is providing me correct combination it looks like this:

Array (18)
0 "1aq"
1 "2aq"
2 "3aq"
3 "1bq"
4 "2bq"
5 "3bq"
6 "1aw"
7 "2aw"
8 "3aw"
9 "1bw"
10 "2bw"
11 "3bw"
12 "1ae"
13 "2ae"
14 "3ae"
15 "1be"
16 "2be"
17 "3be"

But i want (Desired output) it to be like this :

Array (18)
    0 ["1", "a", "q"]
    1 ["2","a","q"]
    2 ["3","a","q"]
    3 ["1","b","q"]
    4 ["2","b","q"]
    5 ["3","b","q"]
    6 ["1","a","w"]
    7 ["2","a","w"]
    8 ["3","a","w"]
    9 ["1","b","w"]
    10 ["2","b","w"]
    11 ["3","b","w"]
    12 ["1","a","e"]
    13 ["2","a","e"]
    14 ["3","a","e"]
    15 ["1","b","e"]
    16 ["2","b","e"]
    17 ["3","b","e"]

Basically i am trying to achieve is a combination array instead of strings.

Upvotes: 0

Views: 655

Answers (1)

baao
baao

Reputation: 73301

Just concat instead of the +:

result.push([a4[0][j]].concat(allCasesOfRest[i]));

to get what you want. You have an string and an array you want to put together - for that you can put the string in an array, then concat that array with the second array you got.

var a1 = ["1", "2", "3"];
var a2 = ["a", "b"];
var a3 = ["q", "w", "e"];

var a4 = [a1, a2, a3];

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

      }
      
      return result;
      
  }
  
  console.log(allPossibleCases(a4));

Upvotes: 2

Related Questions