JavaScript - Generating combinations from n arrays with m elements

前端 未结 10 1789
一个人的身影
一个人的身影 2020-11-22 04:10

I\'m having trouble coming up with code to generate combinations from n number of arrays with m number of elements in them, in JavaScript. I\'ve seen similar questions about

10条回答
  •  Happy的楠姐
    2020-11-22 04:52

    You can use a recursive function to get all combinations

    const charSet = [["A", "B"],["C", "D", "E"],["F", "G", "H", "I"]];
    
    let loopOver = (arr, str = '', final = []) => {
      if (arr.length > 1) {
        arr[0].forEach(v => loopOver(arr.slice(1), str + v, final))
      } else {
        arr[0].forEach(v => final.push(str + v))
      }
      return final
    }
    
    console.log(loopOver(charSet))


    This code can still be shorten using ternary but i prefer the first version for readability

提交回复
热议问题