JavaScript - Generating combinations from n arrays with m elements

前端 未结 10 1599
一个人的身影
一个人的身影 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条回答
  •  礼貌的吻别
    2020-11-22 04:52

    I suggest a simple recursive generator function:

    // Generate all combinations of array elements:
    function* cartesian(head, ...tail) {
      let remainder = tail.length ? cartesian(...tail) : [[]];
      for (let r of remainder) for (let h of head) yield [h, ...r];
    }
    
    
    // Example:
    for (let c of cartesian([0,1], [0,1,2,3], [0,1,2])) {
      console.log(...c);
    }

提交回复
热议问题