How to sort a struct?
I've created a highscore struct that stores the player name and their score but I want to display it from the biggest to the smallest.
I know how to do this with a normal array of int's but not with a struct.
Can anyone help?
asked Oct 22 '15 at 02:43 PM in Blueprint Scripting
There aren't too many good array sorting functions in Blueprint, however there are many ways to achieve this yourself.
The simplest way logically to do this is to create a second array of structs which represents the 'sorted array'. Then run through a for each loop on your original array. In this for each loop, run a "for each loop with break" on this second 'sorted' array. In the second for each loop, check every element to see if your high score property is less than the element you have in your first for loop. If it is, then insert the array element you have from the first for each loop node into the array at the index of the array index output from the second for loop, and break the second loop. If this second for loop node completes without finding a smaller high score, then simply add the array element from the first for loop to the end of the second 'sorted' array.
This will result in logic that will stack your structs in order from highest to lowest score and the result of this sort will be in this second array. You can then assign the first array with the value of this sorted array.
answered Oct 22 '15 at 02:59 PM
I've spent a few hours tonight figuring this out, and I thought I'd post it here for anyone else who comes across this thread. I made a function that performs a selection sort on a struct array; in my case to sort a leaderboard array by score.
And here is the macro I used to swap the array elements:
answered Jan 13 '16 at 11:40 PM
It's also worth mentioning that Rama's Victory Plugin has a Sort node for arrays, and an option to sort by structure or object field. Works fine for me.
(copied my answer from another thread to this one too, for future generations =) )
answered Mar 21 '18 at 05:07 PM
Follow this question
Once you sign in you will be able to subscribe for any updates here