美文网首页
排列:给多个数组,分别依次任取一个进行组合,如[ [1, 2],

排列:给多个数组,分别依次任取一个进行组合,如[ [1, 2],

作者: videring | 来源:发表于2020-02-26 09:54 被阅读0次
    export function combination(originData) {
      /*
      * 给多个数组,如[ [1, 2], [3, 4], [5, 6] ],从几个数组中,分别依次任取一个进行组合,结果为:
      *  [ [1, 3, 5], [1, 3, 6], [1, 4, 5], [1, 4, 6], [2, 3, 5], [2, 3, 6], [2, 4, 5], [2, 4, 6] ]
      * */
      let m = originData
      let arr = []
      let flag = 0 // 从0开始
      let tmp = []
      let currentI
      let currentJ
      while (flag < originData.length - 1) {
        for (let i = 0; i < m[0].length; i++) {
          for (let j = 0; j < m[1].length; j++) {
            currentI = m[0][i]
            currentJ = m[1][j]
            tmp = Array.isArray(currentI)
              ? [...currentI, currentJ]
              : [currentI, currentJ]
            arr.push(tmp)
            tmp = []
          }
        }
        m = [arr, ...originData.slice(flag + 2)]
        arr = []
        flag++
      }
    
      return m
    }
    
    export default {
      combination
    }
    
    

    相关文章

      网友评论

          本文标题:排列:给多个数组,分别依次任取一个进行组合,如[ [1, 2],

          本文链接:https://www.haomeiwen.com/subject/bnopchtx.html