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


i've seen several similar questions how generate possible combinations of elements in array. i'm having hard time figuring out how write algorithm output combination pairs. suggestions super appreciated!

starting following array (with n elements):

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

and getting following result:

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

i trying out following approach results in possible combinations, instead combination pairs.

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

a simple way double loop on array skip first i elements in second loop.

let array = ["apple", "banana", "lemon", "mango"];  let results = [];    // since want pairs, there's no reason  // iterate on last element directly  (let = 0; < array.length - 1; i++) {    // you'll capture last value    (let j = + 1; j < array.length; j++) {      results.push(`${array[i]} ${array[j]}`);    }  }    console.log(results);

rewritten es5:

var array = ["apple", "banana", "lemon", "mango"];  var results = [];    // since want pairs, there's no reason  // iterate on last element directly  (var = 0; < array.length - 1; i++) {    // you'll capture last value    (var j = + 1; j < array.length; j++) {      results.push(array[i] + ' ' + array[j]);    }  }    console.log(results);


Comments