无需重复的javascript组合

时间:2018-11-15 06:03:46

标签: javascript combinations permutation

给予

[
  ["blue", "red"],
  [1, 2],
  [true, false],
]

如何在javascript中获得可能的组合?:

blue, 1, true
blue, 1, false
blue, 2, true
blue, 2, false
red, 1, true
red, 1, false
red, 2, true
red, 2, false

顺序无关紧要。

1 个答案:

答案 0 :(得分:3)

这非常复杂,而且很有趣,因此感谢您提出要求!

在这里我们可以拥有m个任意大小的元素数组,

var a = [
  ["blue", "red"],
  [1, 2],
  [true, false],
]

function allPossibleCombinations(items, isCombination=false){
    // finding all possible combinations of the last 2 items
    // remove those 2, add these combinations
    // isCombination shows if the last element is itself part of the combination series
    if(items.length == 1){
       return items[0]
    }
    else if(items.length == 2){
       var combinations = []
       for (var i=0; i<items[1].length; i++){
           for(var j=0; j<items[0].length; j++){
               if(isCombination){
                   // clone array to not modify original array
                   var combination = items[1][i].slice();
                   combination.push(items[0][j]);
               }
               else{
                   var combination = [items[1][i], items[0][j]];
               }
               combinations.push(combination);
           }
       }
       return combinations
    }
    else if(items.length > 2){
       var last2 = items.slice(-2);
       var butLast2 = items.slice(0, items.length - 2);
       last2 = allPossibleCombinations(last2, isCombination);
       butLast2.push(last2)
       var combinations = butLast2;
       return allPossibleCombinations(combinations, isCombination=true)
    }
}

console.log(allPossibleCombinations(a));
console.log(allPossibleCombinations(a).length);