I\'ve seen several similar questions about how to generate all possible combinations of elements in an array. But I\'m having a very hard time figuring out how to write an a
Although solutions have been found, I post here an algorithm for general case to find all combinations size n
of m (m>n)
elements. In your case, we have n=2
and m=4
.
const result = [];
result.length = 2; //n=2
function combine(input, len, start) {
if(len === 0) {
console.log( result.join(" ") ); //process here the result
return;
}
for (let i = start; i <= input.length - len; i++) {
result[result.length - len] = input[i];
combine(input, len-1, i+1 );
}
}
const array = ["apple", "banana", "lemon", "mango"];
combine( array, result.length, 0);