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

前端 未结 10 1429
南旧
南旧 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条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-27 21:43

    Seeing a lot of for loops in all of the answers...

    Here's a recursive solution I came up with that will find all combinations of N number of arrays by taking 1 element from each array:

    const array1=["A","B","C"]
    const array2=["1","2","3"]
    const array3=["red","blue","green"]
    
    const combine = ([head, ...[headTail, ...tailTail]]) => {
      if (!headTail) return head
    
      const combined = headTail.reduce((acc, x) => {
        return acc.concat(head.map(h => `${h}${x}`))
      }, [])
    
      return combine([combined, ...tailTail])
    }
    
    console.log('With your example arrays:', combine([array1, array2]))
    console.log('With N arrays:', combine([array1, array2, array3]))

提交回复
热议问题