Instagram post shared by @afewminutesofcode
afewminutesofcode

Sort an array by multiple fields in JavaScript.⠀

Sometimes we will want to sort an array by multiple fields.⠀

Take the recent cricket world cup as an example. 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 out image 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.⠀

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 @afewminutesofcode to stay up to date.⠀

Enjoy the rest of the weekend and have a great week!⠀

.⠀
.⠀
.⠀
.⠀
.⠀

#frontend #developers #webdevelopment #peoplewhocode #webdeveloper #programming #js #reactjs #javascript #coding #frontenddeveloper #learntocode #freecodecamp #devlife #buildtheweb #100daysofcode #nodejs #programmer #coder #webdev #html #buildupdevs #developerspace #thedevlife #cricketworldcup #engvnz #cwc19final #cricket #ashes #icc