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)

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

Output

Following is the output in the console −

A

Updated on: 18-Sep-2020

95 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements