Reputation: 45
My first time here I know I should be better at arrays but for some reason this one is stumping me...
I'm creating a 4 player game each player get a number the lowest one loses but...
The way I'm doing it only find the first lowest value in the array and but it seems to ignore the identical number even though they are both the lowest.
I have an array...
var tilesInit = new Array();
tilesInit = {
a:9,
b:9,
c:11,
d:22
}
Then I'm checking for the highest and lowest...
//Find largerest number//
var max = Math.max.apply(null, Object.keys(scores).map(function(e) { return scores[e]; }));
//Find losing player//
var loser = scores.indexOf(max);
//Find lowest number//
var min = Math.min.apply(null, Object.keys(scores).map(function(e) { return scores[e]; }));
//Find winning player//
var winner = scores.indexOf(min);
//
//
console.log("Losing score is: "+max+"\n Losing player is player: "+loser);
console.log("Winning score is: "+min+"\n Winning player is player: "+winner);
But I stumped on a way to recheck it to find the index number of the other lowest number I'm assuming its inside "var min"s .apply() function but I can't seem to figure it out
Thanks for your help, Byron
Upvotes: 0
Views: 142
Reputation: 60143
The simplest thing may be just to do it by hand:
var scores = {
a: 9,
b: 9,
c: 11,
d: 22,
};
function findAllMinimum(scores) {
var minSoFar = Infinity;
var minScorers = [];
Object.keys(scores).forEach(function (player) {
var score = scores[player];
if (score < minSoFar) {
minSoFar = score;
minScorers = [player];
} else if (score === minSoFar) {
minScorers.push(player);
}
});
return minScorers;
}
console.log(findAllMinimum(scores));
// Output:
// [ 'a', 'b' ]
EDIT
Here's a terser but less efficient option using lodash:
function findAllMinimum(scores) {
return _.invertBy(scores)[_.min(_.values(scores))];
}
Another lodash solution, more efficient than the previous one, but still worse than the "by hand" example above:
function findAllMinimum(scores) {
var minScore = _.min(_.values(scores));
return _.filter(_.keys(scores), function (key) {
return scores[key] === minScore;
});
}
Upvotes: 1