DEV Community

Aaron
Aaron

Posted on

1 2

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

Instagram
Facebook
afewminutesofcode.com
Twitter
Pinterest

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

Instrument, monitor, fix: a hands-on debugging session

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️