I came across a pretty complex algorithm that I developed last year that I thought would be challenging and useful of others. So hence…
Coding Challenge
Sort a List of Objects by a property inside of the objects
Remix
The full code and project can be remixed here: Thunkable
Walkthrough
Let’s first define a list of objects to be sorted
We will sort on favorite > number
, so I wrote a helper function that takes in the object and then returns the favorite number
Now let’s write a function to display that list in a list viewer
Whenever the screen starts
or when we press the Shuffle
button, we will display shuffled version of the list
And now we can see what the unsorted list looks like
Now I define the COMPLEX sorting algorithm. In summary:
- If there is nothing in the list, add the object to the list
- If there is one object in the list, see if the current object should go before or after
- If there is more than one object in the list, loop through each object in the list to find where to insert the current object
And now when we press Sort
, we can pass in the unsorted list to the sorting function and get the sorted list!
Closing Thoughts
If you need to use this in your app, I’d encourage you to remix this app (link above) and then copy the screen into your own app, so that you don’t have to block all of this out. See this article:
https://docs.thunkable.com/screen#save-screen
And if you need to sort in descending order then you can just update the Display List
function to insert at first
instead of insert at last
.