Home > Enterprise >  How would I sort the following object array by the VALUES (Score)
How would I sort the following object array by the VALUES (Score)

Time:10-28

`let teams = [  {key: cityTeam, value:playerScore[0]},
{key: 'Green Bay', value:computerScore[0]},
{key: "Chicago", value:chicagoScore[0]},
{key: "Los Angeles", value:laScore[0]},
{key: "New York", value:nyScore[0]},
{key: "Miami", value:miamiScore[0]},
{key: "Houston", value:houstonScore[0]},
{key: "Seattle", value:seattleScore[0]},
{key: "Toronto", value:torontoScore[0]},
{key: "Dallas", value:dallasScore[0]},
{key: "Mexico City", value:mexicoCityScore[0]},
{key: "Detroit", value:detroitScore[0]},
`your text`{key: "Ottawa", value:ottawaScore[0]},
{key: "San Francisco", value:sfScore[0]},
{key: "Denver", value:denverScore[0]},
{key: "Toluca", value:tolucaScore[0]}  ]`

I tried to sort these with all sorts of methods from a for loop from a .sort to a .values Sort (I tried all that I could) I wanted the array to be ranked in descending order from highest to lowest SCORE, but it either did it by the names or didn't sort at all, I spent days trying to solve this and it's not working. And then, it has to print out the top 6 and every time there is a change in ranking, it will change to positioning and print out the new result.

CodePudding user response:

to answer part of your question,

teams.sort(function(a, b) {
  return  a.value -  b.value
})

CodePudding user response:

Read https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

But this should work, be aware that teams become sorted by this, it's not just a sorted copy that is returned.

let teams = [  {key: 'cityTeam', value:playerScore[0]},
{key: 'Green Bay', value:computerScore[0]},
{key: "Chicago", value:chicagoScore[0]},
{key: "Los Angeles", value:laScore[0]},
{key: "New York", value:nyScore[0]},
{key: "Miami", value:miamiScore[0]},
{key: "Houston", value:houstonScore[0]},
{key: "Seattle", value:seattleScore[0]},
{key: "Toronto", value:torontoScore[0]},
{key: "Dallas", value:dallasScore[0]},
{key: "Mexico City", value:mexicoCityScore[0]},
{key: "Detroit", value:detroitScore[0]},
{key: "Ottawa", value:ottawaScore[0]},
{key: "San Francisco", value:sfScore[0]},
{key: "Denver", value:denverScore[0]},
{key: "Toluca", value:tolucaScore[0]}  ]

teams.sort((a,b) => a.value - b.value)
/*
> 0     sort a after b
< 0     sort a before b
=== 0   keep original order of a and b
*/
  • Related