Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
42
rated 0 times [  46] [ 4]  / answers: 1 / hits: 121040  / 7 Years ago, wed, april 5, 2017, 12:00:00

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

More From » arrays

 Answers
82

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




[#58255] Monday, April 3, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dominickmackenziet

Total Points: 583
Total Questions: 101
Total Answers: 117

Location: Saint Lucia
Member since Wed, Feb 8, 2023
1 Year ago
dominickmackenziet questions
Wed, Apr 7, 21, 00:00, 3 Years ago
Fri, Feb 12, 21, 00:00, 3 Years ago
;