views:

78

answers:

3

Consider this:

[ ["a", "b"], ["c", "d"], ["e"] ]

How can this be tranformed to:

[ "a c e", "a d e", "b c e", "b d e" ]
A: 

Try concat method:

var newArr=[];

for(var i=0; i< arr.length; i++)
{ 
   newArr = newArr.concat(arr[i]);
}
TheVillageIdiot
that would just produce ["a", "b", "c", "d", "e"]
snz3
Sorry my fault, I didn't see output you wanted :) programmer's symptom.
TheVillageIdiot
+2  A: 

// edit: tested and works

function product(set) {
 if(set.length < 2)
  return set[0];
 var head = set.shift(), p = product(set), r = [];
 for(var j = 0; j < head.length; j++)
  for(var i = 0; i < p.length; i++)
   r.push([head[j]].concat(p[i]));
 return r;
}

var set = [
 [ "a", "b", "c"],
 [ "D", "E" ], 
 [ "x" ]
];

var p = product(set);
for(var i = 0; i < p.length; i++)
 document.write(p[i] + "<br>");
stereofrog
thank you so much! I knew I had to recurse somewhere but just couldn't find the pattern.
snz3
This code won't run: it is missing ) in two places.
Kinopiko
+1  A: 

This works:

<html><body><script>
var to_join = [ ["a", "b"], ["c", "d"], ["e"] ];
var joined = to_join[0];
for (var i = 1; i < to_join.length; i++) {
    var next = new Array ();
    var ends = to_join[i];
    for (var j = 0; j < ends.length; j++) {
        for (var k = 0; k < joined.length; k++) {
            next.push (joined[k]+ " " + (ends[j]));
        }
    }
    joined = next;
}
alert (joined);
</script></body></html>
Kinopiko
It would work even better if you closed the body tag ;]
Will Morgan
Thank you for your correction.
Kinopiko