JavaScript - Generating combinations from n arrays with m elements

前端 未结 10 1861
一个人的身影
一个人的身影 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:41

    Another implementation with ES6 recursive style

    Array.prototype.cartesian = function(a,...as){
      return a ? this.reduce((p,c) => (p.push(...a.cartesian(...as).map(e => as.length ? [c,...e] : [c,e])),p),[])
               : this;
    };
    
    console.log(JSON.stringify([0,1].cartesian([0,1,2,3], [[0],[1],[2]])));

提交回复
热议问题