How to implement three of a kind?

Wrote on two methods for finding pairs of cards one and two. At a loss how to implement the three / set. Below, two Massimo, which in turn I shove in methods.

[ '2D', '2H', '9S', '9C', 'KD' ]
[ '2C', '2H', '2S', '4C', 'AH' ]


getOnePair function(hand) {

 var cards = hand.slice().sort();
 var pairs = [];

 for(i = 0; i < hand.length - 1; i++) {
 if(cards[i + 1].charAt(0) == cards[i].charAt(0)) {
pairs.push(cards[i].charAt(0));
break;
}
}

 if(pairs.length > 0) {
 return pairs;
 } else {
 return "No pair cards found.";
}

}

getTwoPairs function(hand) {

 var cards = hand.slice().sort();
 var pairs = [];

 for(i = 0; i < hand.length - 1; i++) {
 if(cards[i + 1].charAt(0) == cards[i].charAt(0)) {
 if(pairs.indexOf(cards[i].charAt(0)) == -1) {
pairs.push(cards[i].charAt(0));
}
}
}

 if(pairs.length > 1) {
 return pairs;
 } else {
 return "two pair No cards found.";
}

}
July 4th 19 at 22:57
2 answers
July 4th 19 at 22:59
You would have to check on the number would make the view object {tipcart: colechester}, and since everything can be checked.
Not quite you understand - carole.Graha commented on July 4th 19 at 23:02
: convert source array to the view object: {'2': 3, '4' : 1, 'A': 1}, it is easy to determine all the combinations based on the combination of matching cards. - willow.Hand commented on July 4th 19 at 23:05
July 4th 19 at 23:01
You can slightly change the principle and this dance
var arr = [ '2D', '2H', '9S', '9C', 'KD' ];

function countCardsByType(cardsArr){
 var count = {};

 for(i = 0; i < cardsArr.length - 1; i++) {
 var cardType = cardsArr[i].charAt(0);
 count[cardType] = typeof count[cardType] == "number"? count[cardType] + 1: 1;
}
 return count;
}

function getSets(cardsArr, numberInSet, countOfSets) {

 var cards = cardsArr.slice().sort();
 var countOfCardsTypes = countCardsByType(cards);

 var sets = [];

 for(var type in countOfCardsTypes) {
 var count = countOfCardsTypes[type];
 if(count == numberInSet){
sets.push(type);
}
}
 if(sets.length == countOfSets) {
 return sets;
 } else {
 return "No cards found";
}

}
//will return an array of the cards only if the deck 1 pair
console.log(getSets(arr, 2, 1));
//will return an array of the cards only if the deck 2 pairs
console.log(getSets(arr, 2, 2));
//will return an array of the cards only if the deck 1 set
console.log(getSets(arr, 3, 1));

Find more questions by tags JavaScript