1

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" ] 

3 Answers 3

2

// 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>"); 
Sign up to request clarification or add additional context in comments.

1 Comment

thank you so much! I knew I had to recurse somewhere but just couldn't find the pattern.
1

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> 

Comments

0

Try concat method:

var newArr=[]; for(var i=0; i< arr.length; i++) { newArr = newArr.concat(arr[i]); } 

2 Comments

that would just produce ["a", "b", "c", "d", "e"]
Sorry my fault, I didn't see output you wanted :) programmer's symptom.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.