How can I create every combination possible for the contents of two arrays?

前端 未结 10 1428
南旧
南旧 2020-11-27 20:44

I have two arrays:

var array1=[\"A\",\"B\",\"C\"];

var array2=[\"1\",\"2\",\"3\"];

How can I set another array to contain every combinatio

10条回答
  •  萌比男神i
    2020-11-27 21:39

    one more:

    const buildCombinations = (allGroups: string[][]) => {
      const indexInArray = new Array(allGroups.length);
      indexInArray.fill(0);
      let arrayIndex = 0;
      const resultArray: string[] = [];
      while (allGroups[arrayIndex]) {
        let str = "";
        allGroups.forEach((g, index) => {
          str += g[indexInArray[index]];
        });
        resultArray.push(str);
        // if not last item in array already, switch index to next item in array
        if (indexInArray[arrayIndex] < allGroups[arrayIndex].length - 1) {
          indexInArray[arrayIndex] += 1;
        } else {
          // set item index for the next array
          indexInArray[arrayIndex] = 0;
          arrayIndex += 1;
          // exclude arrays with 1 element
          while (allGroups[arrayIndex] && allGroups[arrayIndex].length === 1) {
            arrayIndex += 1;
          }
          indexInArray[arrayIndex] = 1;
        }
      }
      return resultArray;
    };
    

    One example:

    const testArrays = [["a","b"],["c"],["d","e","f"]]
    const result = buildCombinations(testArrays)
    // -> ["acd","bcd","ace","acf"]
    

提交回复
热议问题