DEV Community π©βπ»π¨βπ» is a community of 968,547 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Aaron

Posted on

How the winner of the cricket world cup was awarded in Javascript

In this post we are going to use a practical example from a recent sporting event to learn how to sort an array by multiple fields in JavaScript.

In the recent cricket world cup, The winner was decided based on the below.β 

• Most runs (if a tie go to a super over)β 
• Most runs in Super Over (if a tie go to a boundary count)β 
• Most boundaries.β 

When sorting we can use the syntax `array.sort((a,b) => b - a` to sort from highest to lowest.β 

So in our code below we check β 

• if the runs and super over runs are equal - sort by boundary countβ 
• else if runs are equal sort by most runs in super overβ 
• else sort by most runsβ 

Then because this will sort an array we the take the first results in the array [0] and return the team property, so when we log out the scores from the world cup final we can see that England is declared the winner of the match.β 

``````const cricketWorldCupFinal = [{
team: 'England',
runs: 241,
wkts: 10,
supOvrRuns: 15,
boundaryCount: 26
},
{
team: 'New Zealand',
runs: 241,
wkts: 8,
supOvrRuns: 15,
boundaryCount: 17
}]

const calcMatchWinner = scores => {
return scores.sort((a, b) => {
if (a.runs === b.runs && a.supOvrRuns === b.supOvrRuns) {
return b.boundaryCount - a.boundaryCount
} else if (a.runs === b.runs) {
return (b.supOvrRuns - a.supOvrRuns)
} else {
return (b.runs - a.runs)
}
})[0].team
}

console.log(calcMatchWinner(cricketWorldCupFinal))
// output => England
``````

I am currently working on a cricket javascript course where I demonstrate how to Create a Cricket Points Table in JavaScript so please follow me on one of the below channels or here on Dev to stay up to date, with when it is released.β 