Sorting the Scores of an Array of Player Objects. -JavaScript-
I was having some trouble sorting by the highest score from an array of player objects. After doing some digging I found a way that was much simpler than I had first anticipated. This is a rundown of how it’s done.
First will start with our array of player objects.
As you can see we have an array with five player objects, each player has a name and a score. The goal is to console.log the array with the players arranged by score, from highest to lowest.
In order to achieve this, we will use javascript’s built-in array.prototype method, .sort(), the .sort() method is by itself intended to compare strings, but if we use a comparison function as an argument in our sort method we can get our desired outcome. Let's create a function called sortedHighToLowPlayers and implement this.
Now we just console.log(sortedHighToLowPlayers(players)) to see if our function has the desired effect.
Perfect! Our players have been sorted by their scores from highest to lowest! To sort our player scores from lowest to highest simply reverse the return of our comparison function inside of the .sort() method.
And if our score data type happens to be a string instead of an integer, just parseInt in the return arguments from our comparison function
So that’s a simple rundown of how to sort by number values of an object’s properties. Thanks for reading!
Resources:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort