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

2020-02-26  本文已影响0人  videring
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
}

上一篇下一篇

猜你喜欢

热点阅读