htoniv
htoniv

Reputation: 1668

combine N number of array values in javascript

var arr= [[1,2,3],[1,2],[1,2,3,4]];

following is my static sample array. here what i done is combining first,second & third array values.

for (var a1=0;a1<arr[0].length;a1++) {
    for (var a2=0;a2<arr[1].length;a2++) {
        for (var a3=0;a3<arr[2].length;a3++) {
            console.log(arr[0][a1]+""+arr[1][a2] + "" +arr[2][a3]);
        }
    }
}
//Output
//111,112,113,114,121,122,123,124
//211,212,213,214,221,222,223,224
//311,312,313,314,321,322,323,324

[[1,2,3],[1,2]]
So in here how i combining values is // 11,12,21,22,31,32

So in future the arrays wont be static. Is there any built-in javascript function to do the same

or how can i make this dynamic?

Upvotes: 0

Views: 124

Answers (1)

Pavel Gatnar
Pavel Gatnar

Reputation: 4053

You can use Array.reduce with this callback:

function combine(p,v){
  var r = []
  for(var i=0;i<p.length;i++){
    for(var j=0;j<v.length;j++){
      r.push([p[i],v[j]].join(''))
    }
  }
  return r
}
var x = a.reduce(combine,[''])

Upvotes: 5

Related Questions