I have 8 players ab
,cd
,ef
,gh
,ij
,kl
,mn
,op
their match data is stored in an array of objects
matchData=[
{player1:'ab',player2:'cd',winner:'ab',looser:'cd'},
{player1:'ef',player2:'gh',winner:'gh',looser:'ef'},
{player1:'ij',player2:'kl',winner:'ij',looser:'kl'},
{player1:'mn',player2:'op',winner:'mn',looser:'op'},
{player1:'ab',player2:'cd',winner:'ab',looser:'cd'},
{player1:'ij',player2:'kl',winner:'kl',looser:'ij'},
{player1:'ij',player2:'kl',winner:'ij',looser:'kl'}]
I want to get the top player from the above match data.The Top player is the one who is having the highest win rate
winrate=(number of matches won/total number of matches played)*100
And also want to get the array of objects which look like,
PlayerData=[{ab:87},{cd:78},{ef:57},{gh:75},{ij:47},{kl:14},{mn:65},{op:44}]
How can I do this?
You can loop though data and create new array for each winner/looser adding in 1 if wins else 0 if looses. Then calculate percentage of wins from new array object.
matchData = [
{player1:'ab',player2:'cd',winner:'ab',looser:'cd'},
{player1:'ef',player2:'gh',winner:'gh',looser:'ef'},
{player1:'ij',player2:'kl',winner:'ij',looser:'kl'},
{player1:'mn',player2:'op',winner:'mn',looser:'op'},
{player1:'ab',player2:'cd',winner:'ab',looser:'cd'},
{player1:'ij',player2:'kl',winner:'kl',looser:'ij'},
{player1:'ij',player2:'kl',winner:'ij',looser:'kl'}
]
let tempRes = {}
for (let d of matchData) {
let { winner, looser } = d
tempRes[winner] = (tempRes[winner] || []).concat(1)
tempRes[looser] = (tempRes[looser] || []).concat(0)
}
let res = [], topPlayers = [], topValue = 0
for (let [key, value] of Object.entries(tempRes)) {
let winPercent = (value.reduce((a,b) => a + b) / value.length) * 100
res.push({ [key]: winPercent })
winPercent == topValue && (topPlayers.push(key))
winPercent > topValue && (topValue = winPercent, topPlayers = [key])
}
console.log('Top Player ', topPlayers)
console.log('Result ',res)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments