0

I need to make a function that receives an array and generates all combinations based on N param size. Example:

function comb([1,2],3)
out: 
[[1,1,1],
[1,1,2],
[1,2,1],
[1,2,2],
[2,1,1],
[2,1,2],
[2,2,1],
[2,2,2]]

or:

function comb([4,1],2)
out:
[[4,4],
[4,1],
[1,4],
[1,1]]
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437

1 Answers1

0

I found a solution from Nina Scholz
JavaScript - Generating combinations from n arrays with m elements

and i made an adaptation, this is the result:

var result = 0;
function combination(parts,N){
    var parts_normalize = []
  while (N--) parts_normalize.push(parts)
    result = parts_normalize.reduce((a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), []));
  console.log(result)
}

this is working well but, someone can explain what is happening in this function xD i am totaly lost