JSFiddle - React, Tailwind, and code Playground
CSS
div#output {
padding: 20px;
}
JavaScript
var leaderboard = [{userId: 10293, balance: 1023},
{userId: 20394, balance: 1806},
{userId: 45333, balance: 2064},
{userId: 57456, balance: 2453},
{userId: 24575, balance: 2703}
];
leaderboard.max = -Infinity; // Set max balance
leaderboard.min = Infinity; // Set min balance
leaderboard.forEach( function( item, index, self ) {
if (item.balance>self.max) self.max = item.balance;
if (item.balance<self.min) self.min = item.balance;
});
leaderboard.updateBalance = function ( userId, newBalance ) {
var updated = false;
var minIndex1 = -Infinity;
var minIndex2 = Infinity;
this.forEach( function( item, index, self ) {
// Find 2 index with minimal balance
if (item.balance === self.min) minIndex1 = index;
if (item.balance > self.min && item.balance < minIndex2) minIndex2 = index;
// If find user - update balance and min and max
if (item.userId === userId) {
updated = true; // Flag - user balance updated
self[index].balance = newBalance;
if (newBalance > self.max) self.max = newBalance;
if (newBalance < self.min) self.min = newBalance;
}
});
// No user find? Push
if (!updated && newBalance > leaderboard.max) {
this.min = this[minIndex2].balance;
if (this.length===5) this.splice(minIndex1, 1); // Remove user with minimal balance
this.max = newBalance;
this.push( { userId: userId, balance: newBalance } );
}
};
leaderboard.updateBalance( 5745, 3500 );
leaderboard.updateBalance( 57, 37000 );
console.log(leaderboard);