0

I have a snake game which at the moment displays a ul on the html page with each player and their id, score, kills and length. What I'm trying to do is get that list to have a max of 3 items and going from the highest score, to the lowest.

It's just the sorting the snakes into another array with the top 3 being the ones with the highest score that's the problem. I can store every snake in the topSnakes array just fine, but after I do topSnakes.sort and try and read anything in it, it will come back as undefined. Any help is appreciated.

Rachel Dockter
  • 946
  • 1
  • 8
  • 21
  • Possible duplicate of [Javascript object list sorting by object property](http://stackoverflow.com/questions/2466356/javascript-object-list-sorting-by-object-property) – rlemon Feb 02 '17 at 12:23

1 Answers1

1
topSnakes=Object.values(snakes).sort((a,b)=>b.Score-a.Score).slice(0,3);

Sort after Score ( biggest first ), than take the first three elems. Your mistake is in the first loop, wich is unnecessary in my opinion...

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151