Andrew Kim - 6 months ago 3x
Javascript Question

Compare 2 or more sorted arrays javascript

I'm trying to handroll a solution for poker. I've gotten all the logic to determine the best 5 card hand. I'm having issues comparing multiple arrays for which have higher elements in the event of ties(with regard to hand type).

Say we have some potential winners for a flush.

``````var low_flush = [2, 3, 4, 5, 7]
var medium_flush = [3, 4, 5, 6, 8]
var high_flush = [2, 3, 4, 5, 9]
``````

I want to build a function that i pass any number of arrays to and it returns the "highest poker hand" or an array of hands in the event of an actual tie:

``````function bestHand(hands){
//
return high_hand
}
``````

Everything I've read thus far is how to compare just two arrays, and usually with that, it only sees if there are equal to each other. If it helps heres my source code

My first thoughts are to iterate over the hands. And for each iteration, iterate over the hands again for comparison. Just thinking about this pseudocode is making my head hurt and was thinking their might be a more elegant solution for this and/or library(not a poker library though)

I am using underscore in other parts of the codebase so feel free to use it in answer as well!

This may seem silly. But this seems to work for me.

``````var hands = [ [2, 3, 4, 5, 7], [2, 3, 5, 9, 8], [2, 3, 4, 5, 9] ];
var values = [];
function bestHand(hands){
hands.forEach(function(arr, index) {
var temp = arr.slice();
values[index] = parseInt(temp.sort().reverse().join(''));
});
var max = Math.max.apply(Math, values);
return hands[values.indexOf(max)];
}
bestHand(hands);
``````
Source (Stackoverflow)