Learn how to easily count and build how many pairs is it possible to form from an array of strings in JavaScript.

In the last few days, I had to answer a couple of technical questions for a job that I found interesting. The problem was about a tool that should form the pairs for the duels of a chess tournament, knowing that the order of the opponents in a pair does not matter. The example is the following one, suppose that you have an array with 4 single items:

["A", "B", "C", "D"]

The goal of the exercise is to determine how many (or which) possible combinations can you form with those items without repeating them as it's a feature that may be needed when calculating how many possible matches can you build for some game like chess e.g AC is the same as CA, so it would be a single match. The following image represents the possible combinations that you can build with the given array:

Possible Pairs from array of strings JavaScript

In this case, the number of possible pairs with 4 items is 6. That's all we need to calculate, just the number of possible pairs starting from a single integer. So the idea would be to create a function that returns that number just like:

// Should output: 6
console.log(count(4));

Having said that, let's get started!

Implementation

The logic to solve this problem is actually simple (and it will be simpler in code):

  1. Iterate over the number of items except for the last one. For example with 4 items, the first loop should iterate only 3 times. In this case, the iteration index starts at 0.
  2. Inside the first loop, another loop will iterate over the number of items again, however, it will ignore all the items whose index is lower than the iteration index of the first loop plus one. Inside this loop, you should be able either to build the possible pair with both indexes or add a number to a counter that adds the new possible pair.

In case that you need which are the pairs that can be formed using the mentioned logic, the following code snippet should do the trick:

function buildPossiblePairsFromArray(array)
{
    let results = [];
    
    for (let i = 0; i < array.length - 1; i++) {
        for (let j = i + 1; j < array.length; j++) {
            results.push(`${array[i]}${array[j]}`);
        }
    }

    return results;
}


// Returns: ["AB", "AC", "AD", "BC", "BD", "CD"]
buildPossiblePairsFromArray(["A", "B", "C", "D"]);

However, if just like me, you just need the number of possible combinations, then the following snippet should work as well:

function count(n){
    let results = 0;

    for (let i = 0; i < n - 1; i++) {
        for (let j = i + 1; j < n; j++) {
            results++;
        }
    }

    return results;
}

// Should Return: 6
count(4);

// Should Return: 45
count(10);

// Should Return: 199990000
count(20000);

Happy coding ❤️!


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors