javascriptarraysalgorithmcombinations

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


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 algorithm that will only output combination pairs. Any suggestions would be super appreciated!

Starting with the following array (with N elements):

var array = ["apple", "banana", "lemon", "mango"];

And getting the following result:

var result = [
   "apple banana"
   "apple lemon"
   "apple mango"
   "banana lemon"
   "banana mango"
   "lemon mango"
];

I was trying out the following approach but this results in all possible combinations, instead only combination pairs.

var letters = splSentences;
var combi = [];
var temp= "";
var letLen = Math.pow(2, letters.length);

for (var i = 0; i < letLen ; i++){
    temp= "";
    for (var j=0;j<letters.length;j++) {
        if ((i & Math.pow(2,j))){ 
            temp += letters[j]+ " "
        }
    }
    if (temp !== "") {
        combi.push(temp);
    }
}

Solution

  • A simple way would be to do a double for loop over the array where you skip the first i elements in the second loop.

    let array = ["apple", "banana", "lemon", "mango"];
    let results = [];
    
    // Since you only want pairs, there's no reason
    // to iterate over the last element directly
    for (let i = 0; i < array.length - 1; i++) {
      // This is where you'll capture that last value
      for (let j = i + 1; j < array.length; j++) {
        results.push(`${array[i]} ${array[j]}`);
      }
    }
    
    console.log(results);

    Rewritten with ES5:

    var array = ["apple", "banana", "lemon", "mango"];
    var results = [];
    
    // Since you only want pairs, there's no reason
    // to iterate over the last element directly
    for (var i = 0; i < array.length - 1; i++) {
      // This is where you'll capture that last value
      for (var j = i + 1; j < array.length; j++) {
        results.push(array[i] + ' ' + array[j]);
      }
    }
    
    console.log(results);