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

all possible subsets of an array javascript
javascript combinations of two arrays
generate all possible combinations
2d array all possible combinations
javascript generate all permutations of string
how many pairs it is possible to form javascript
write a javascript function that generates all combinations of a string
get all subarrays of an array javascript

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

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

How to Calculate the Probability of Combinations, How do you find all the combinations of an array? Count pairs of elements such that number of set bits in their OR is B[i] Count pairs in an array containing at least one even value; Count pairs in an array such that LCM(arr[i], arr[j]) > min(arr[i],arr[j]) Count of odd and even sum pairs in an array; Count of pairs (x, y) in an array such that x < y; Find the sum of all possible pairs in an

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

Print all possible combinations of r elements in a given array of size n, , we will use the formula nCr = n! / r! * (n - r)!, where n represents the number of items, and r represents the number of items being chosen at a time. Similar to above method, we create a temporary array sol[] of size r and for every element in the input array recur for 2 cases. Algorithm. 1. The element is included in current combination ie, we put the data in sol[] and increment the index 2. The element is excluded in current combination ie, we do not put the element and do not change index.

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

Generating all combinations of an array, How do you print all possible combinations of an array? Length of array pair formed where one contains all distinct elements and other all same elements; Minimum sum of the elements of an array after subtracting smaller elements from larger; Maximize sum of K elements in Array by taking only corner elements; Split an array containing N elements into K sets of distinct elements

I ended up writing a general solution to this problem, which is functionally equivalent to nhnghia's answer, but I'm sharing it here as I think it's easier to read/follow and is also full of comments describing the algorithm.

/**
 * Generate all combinations of an array.
 * @param {Array} sourceArray - Array of input elements.
 * @param {number} comboLength - Desired length of combinations.
 * @return {Array} Array of combination arrays.
 */
function generateCombinations(sourceArray, comboLength) {
  const sourceLength = sourceArray.length;
  if (comboLength > sourceLength) return [];

  const combos = []; // Stores valid combinations as they are generated.

  // Accepts a partial combination, an index into sourceArray, 
  // and the number of elements required to be added to create a full-length combination.
  // Called recursively to build combinations, adding subsequent elements at each call depth.
  const makeNextCombos = (workingCombo, currentIndex, remainingCount) => {
    const oneAwayFromComboLength = remainingCount == 1;

    // For each element that remaines to be added to the working combination.
    for (let sourceIndex = currentIndex; sourceIndex < sourceLength; sourceIndex++) {
      // Get next (possibly partial) combination.
      const next = [ ...workingCombo, sourceArray[sourceIndex] ];

      if (oneAwayFromComboLength) {
        // Combo of right length found, save it.
        combos.push(next);
      }
      else {
        // Otherwise go deeper to add more elements to the current partial combination.
        makeNextCombos(next, sourceIndex + 1, remainingCount - 1);
      }
        }
  }

  makeNextCombos([], 0, comboLength);
  return combos;
}

Find all the combinations of the array values in JavaScript , function combinations(str) { var fn = function(active, rest, a) { if (!active && !rest) it permutations ; a permutation is an arrangement of all the original elements (of which (Once JS gets tail-call optimisation, some recursive approaches will run faster.) I have two solutions for this, one being binary and one being recursive;. Efficient approach: First find out the number of unique elements in an array. Let the number of unique elements be x. Then, the number of unique pairs would be x2. This is because each unique element can form a pair with every other unique element including itself.

Using map and flatMap the following can be done (flatMap is only supported on chrome and firefox)

var array = ["apple", "banana", "lemon", "mango"]
array.flatMap(x => array.map(y => x !== y ? x + ' ' + y : null)).filter(x => x)

Javascript get all possible combinations of array, Javascript - Generating all combinations of elements in a single array (in pairs). 03-10 19:52. I've seen several similar questions about how to generate all  In the permutation(2,3) function, the loop will increase the value of 'i' and will point to the element with index 3 in the array. Also, the variable 'start' is 2 and to continue further, we need to swap these two elements as we were doing above. You can also say that the element with the index 2 was the last fixed element.

Generating combinations of k from n entries - JavaScript, Get the all arrays in an array. Recursion is used to solve the problem. The base condition is, When the length of the array reduces to one then return that element​  I would like to generate a list of all possible 4-tuple pairs given an array of size n.n is at least 8, so it is always possible to find at least 1 pair.. As an example that helps to understand the problem I use a smaller version of the problem, 2-tuple pairs given an arrayy of size 5.

JavaScript function: Get all possible subset with a fixed length , Print all possible combinations of r elements in a given array of size n Table of Results should be: How to generate all Permutations - posted in C/C++ have another array that holds every “numeral value”, one per element. js. in a new array containing each pair between each element in each array. The goal was to find all possible combinations of choosing k elements from a n-sized array (basically the Binomial coefficient) and return them. Unlike this code - here I don't want all possible combinations, just those that are k in size. Permutations inside a k-size element are not counted (i.e. (1,2,3) == (2,1,3) == etc.).

Generate all combinations of an array, Javascript - Generating all combinations of elements in a single array (in pairs). Question. I've seen several similar questions about how to generate all possible  This problem has existing recursive solution please refer Print all possible combinations of r elements in a given array of size n link. We will solve this problem in python using itertools.combinations() module.

Comments
  • Add some spread operator for more beauty instead of concat(). :D
  • Your second answer is better written using flatMap() in order to not have nested arrays of subsets: result = [...array.flatMap((v1,i) => array.slice(i+1).map(v2 => v1+' '+v1))]
  • Thanks for your comment, @Phrogz. I updated my answer. When I wrote this answer in 2017, flatMap was not yet widely available. NB: here there is no need to spread the result of flatMap.
  • Please consider adding some comments on how your code achieves the result so it would be easier for others to understand
  • Thank you! for your suggestion