Finding matching pair from an array in JavaScript

We are required to write a JavaScript function that takes in an array of integers that might contain some repeating values. Our function should find out the number of pairs of identical integers we can extract out of the array.

For example, if the input array is:

const arr = [1, 5, 2, 1, 6, 2, 2, 9];

Then the output should be:

const output = 2;

because the desired pairs are (1, 1) and (2, 2). Note that we have three 2's, but we can only form one pair from them.

Using Sorting Approach

The most straightforward approach is to sort the array first, then iterate through it to find consecutive identical elements:

const arr = [1, 5, 2, 1, 6, 2, 2, 9];

const countPairs = (arr = []) => {
    const { length } = arr;
    let count = 0;
    // making a shallow copy so that the original array remains unaltered
    const copy = arr.slice();
    copy.sort((a, b) => a - b);
    
    for(let i = 0; i < length; i++){
        if(copy[i] === copy[i + 1]){
            i++; // skip the next element as it's already paired
            count++;
        }
    }
    return count;
};

console.log(countPairs(arr));
2

Using Frequency Map Approach

An alternative approach uses a frequency map to count occurrences, then calculates pairs mathematically:

const arr = [1, 5, 2, 1, 6, 2, 2, 9];

const countPairsWithMap = (arr = []) => {
    const frequency = {};
    let pairCount = 0;
    
    // Count frequency of each element
    for(let num of arr) {
        frequency[num] = (frequency[num] || 0) + 1;
    }
    
    // Calculate pairs from frequencies
    for(let count of Object.values(frequency)) {
        pairCount += Math.floor(count / 2);
    }
    
    return pairCount;
};

console.log(countPairsWithMap(arr));
2

Comparison

Method Time Complexity Space Complexity Best For
Sorting O(n log n) O(n) Simple implementation
Frequency Map O(n) O(n) Better performance on large arrays

How It Works

Both approaches work by identifying duplicate elements:

  • Sorting method: Groups identical elements together, then pairs them sequentially
  • Frequency map: Counts each element's occurrences, then divides by 2 to get possible pairs

Conclusion

The frequency map approach is more efficient with O(n) time complexity, while the sorting approach is simpler to understand. Choose based on your performance requirements and code clarity preferences.

Updated on: 2026-03-15T23:19:00+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements