Returning poker pair cards - JavaScript

We are required to write a function that takes in an array of exactly five elements representing the five cards of a poker player drawn randomly.

If the five cards contain at least one pair, our function should return the card number of the highest pair (trivial if there only exists a single pair). Else our function should return false.

For example: If the array is −

const arr = ['A', 'Q', '3', 'A', 'Q'];

Then our function should return −

'A'  (as 'A' > 'Q' in card games)

Card Ranking System

In poker, cards are ranked from lowest to highest: 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K, A. We use a legend string to represent this ordering for easy comparison.

Algorithm Approach

The solution works by:

  1. Finding all cards that appear more than once (pairs)
  2. Sorting these pairs by their poker rank
  3. Returning the highest-ranked pair

Example

Following is the code −

const arr = ['A', 'Q', '3', 'A', 'Q'];

const greatestPair = arr => {
    const legend = '23456789JQKA';
    const pairs = [];
    
    for(let i = 0; i < arr.length; i++){
        if(i !== arr.lastIndexOf(arr[i])){
            pairs.push(arr[i]);
        };
    };
    
    if(!pairs.length){
        return false;
    };
    
    pairs.sort((a, b) => legend.indexOf(b) - legend.indexOf(a));
    return pairs[0];
};

console.log(greatestPair(arr));
A

Testing Different Scenarios

Let's test the function with different card combinations:

// Multiple pairs - should return highest
console.log(greatestPair(['K', '2', '7', 'K', '2'])); // K

// Single pair
console.log(greatestPair(['J', '5', 'J', '9', '3'])); // J

// No pairs
console.log(greatestPair(['A', 'K', 'Q', 'J', '9'])); // false

// Three of a kind (still counts as pairs)
console.log(greatestPair(['8', '8', '8', '4', '2'])); // 8
K
J
false
8

How It Works

The function uses lastIndexOf() to detect duplicates. If a card's first occurrence index differs from its last occurrence index, it appears multiple times. The legend string enables proper sorting by poker rank rather than alphabetical order.

Conclusion

This solution efficiently identifies and returns the highest-ranked pair from a poker hand. The legend-based sorting ensures correct poker card rankings are maintained.

Updated on: 2026-03-15T23:18:59+05:30

202 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements