ChrisB's solution had an error, he did not take the length of the loop before arr.shift, and he did not return the last combination, so I think this will complete the task:
function getCombinations(arr, n){ var i,j,k,elem,l = arr.length,childperm,ret=[]; if(n == 1){ for(var i = 0; i < arr.length; i++){ for(var j = 0; j < arr[i].length; j++){ ret.push([arr[i][j]]); } } return ret; } else{ for(i = 0; i < l; i++){ elem = arr.shift(); for(j = 0; j < elem.length; j++){ childperm = getCombinations(arr.slice(), n-1); for(k = 0; k < childperm.length; k++){ ret.push([elem[j]].concat(childperm[k])); } } } return ret; } i=j=k=elem=l=childperm=ret=[]=null; } getCombinationss([["A"],["B"],["C","D"]], 2); //[["A", "B"], ["A", "C"], ["A", "D"], ["B", "C"], ["B", "D"]] getCombinationss([["A"],["B"],["C"],["D"]], 2); //[["A", "B"], ["A", "C"], ["A", "D"], ["B", "C"], ["B", "D"], ["C", "D"]]
Javier cobos
source share