Generate unique pairs with JavaScript


This post goes over how to generate unique pairs with JavaScript.

Problem

Given an array:

[1, 2, 3]

How do you generate unique pairs like the following?

[
  [1, 2],
  [1, 3],
  [2, 3]
]

Solution

The approach is to iterate through the array if the length is greater than 2:

const array = [1, 2, 3];
const pairs = [];

for (const value of array) {
  // ...
}

Then create a sliced copy of the array and form the pairs:

const copy = array.slice(array.indexOf(value) + 1);

for (const element of copy) {
  pairs.push([value, element]);
}

Here’s a function that uses native Array methods:

function uniquePairs(array) {
  if (!Array.isArray(array)) {
    throw new TypeError('First argument must be an array');
  }

  if (array.length < 3) {
    return [array];
  }

  return array.reduce(
    (previousValue, currentValue, index) =>
      previousValue.concat(
        array.slice(index + 1).map((value) => [currentValue, value])
      ),
    []
  );
}

Demo

Replit:



Please support this site and join our Discord!