DEV Community


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)

// 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.⠀


Top comments (0)