Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);     } } 
like image 349
dhdz Avatar asked Apr 05 '17 20:04

dhdz


People also ask

How do you generate all possible combinations of one list?

Add a Custom Column to and name it List1. Enter the formula =List1. Expand out the new List1 column and then Close & Load the query to a table. The table will have all the combinations of items from both lists and we saved on making a custom column in List1 and avoided using a merge query altogether!


Video Answer


1 Answers

Here are some functional programming solutions:

Using EcmaScript2019's flatMap:

var array = ["apple", "banana", "lemon", "mango"];    var result = array.flatMap(      (v, i) => array.slice(i+1).map( w => v + ' ' + w )  );    console.log(result);

Before the introduction of flatMap (my answer in 2017), you would go for reduce or [].concat(...) in order to flatten the array:

var array = ["apple", "banana", "lemon", "mango"];    var result = array.reduce( (acc, v, i) =>      acc.concat(array.slice(i+1).map( w => v + ' ' + w )),  []);    console.log(result);

Or:

var array = ["apple", "banana", "lemon", "mango"];    var result = [].concat(...array.map(       (v, i) => array.slice(i+1).map( w => v + ' ' + w ))  );    console.log(result);
like image 82
trincot Avatar answered Oct 26 '22 16:10

trincot