Javascript - Generating all combinations of elements in a single array (in pairs)

后端 未结 9 615
天命终不由人
天命终不由人 2020-11-28 11:14

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

9条回答
  •  抹茶落季
    2020-11-28 11:50

    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);

提交回复
热议问题