jquery - I have a javascript object, and I want to find a user by id and update their balance -


var leaderboard = [{userid: 10293, balance: 1023},                    {userid: 20394, balance: 1806},                    {userid: 45333, balance: 2064},                    {userid: 57456, balance: 2453},                    {userid: 24575, balance: 2703}                   ]; 

i have object , want create function searches see if user added checking userids. if exist want update specific balance new one, in case msg.userbalance. if don't exist want check if balance greater 1 of balances in object, , if want add them , remove 6th 1 lowest balance.

leaderboard.map(function(person) {   if (person.userid == msg.userid) {     person.balance = msg.userbalance   } else {     if (currentbalance > //other 5 balances in object {        leaderboard.push({userid: msg.userid, balance: msg.userbalance});     }   } }); 

i'm bit stuck , know i'm in right direction missing big part of equation. i'm not opposed using jquery i'm looking simple solution. help?

i think want,,

var user = leaderboard.filter(function(user){return userid == msg.userid})[0]; if(user){    user.balance = msg.userbalance; } else {    leaderboard.push({userid: msg.userid, balance: msg.userbalance});    leaderboard.sort(function(a,b){return a.balance-b.balance});    leaderboard.shift();      } 

what did here ,, used filter user matches target user id ,, , if wasn't found ,, add array ,, , sort array ascending ,, , remove first element ,, lowest one


Comments