Joining each item of an array with the items of another array
Consider this:
[ ["a", "b"], ["c", "d"], ["e"] ]
How can this be tranf开发者_JAVA技巧ormed to:
[ "a c e", "a d e", "b c e", "b d e" ]
// 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>");
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>
Try concat method:
var newArr=[];
for(var i=0; i< arr.length; i++)
{
newArr = newArr.concat(arr[i]);
}
精彩评论