Trying to sort an array by an integer variable

So i have an initiative system like dungeons and dragons or baldurs gate 3. When combat is called, all BP_BaseCharacter’s do the initiative roll function. This sets the integer variable “InitiativeSet” and then sends that actor to an Array in a gamestate blueprint i have called CombatState. I then want this array of actors to be sorted by their “InitiativeSet” variable. Is this possible in blueprints? Or is there another way i could accomplish this goal?

this is possible. but my experience tells me it’s better not to sort the actors list as you might want to use it in other places for other purposes.
you can do this.
treat each index in that array as an “id”. (which means don’t move the actor in the actor list, and if you do, consider your ids invalid).

then when iterating just use an list of the order.
for example. you have 5 actors
actors = { a ,b,c,d,e}
then you have a list of their initiatives, use their ids as values
init = {0,1,2,3,4}
that’s the default order. you do your math to come up with the correct order, like
init = {4,3,2,1,0}

then when you need to iterate them, you use it through the initiatives list

num_inits = init.Num() (or size, this size should be the same as actors)
for i in 0..num_inits:
id = init[i]
act = actors[id]
do whatever you need here

that way your sort will be faster since it doesn’t copy large objects (though actors are probably pointers so it would be fast).
but also allows you to iterate the actors by initiative and also by regular order.
so you can still process them in the ui correctly. for example .

(it’s been quite a while since i had the pleasure to play d&d i hope i got it right)

Here’s a post with a bunch of examples on implementing lots of different sorting algorithms in blueprint. Just change the Blueprint after the GET nodes to grab your InitiativeSet variable. Quicksort is probably the best, but if you have a small array (under 20 or 30 items), insertion sort is probably good enough.

There’s even a zip file with the blueprints.

If you have access to C++ in your project and your InitiativeSet variable is defined in C++, I’d use C++ as it’s way easier and faster than anything in blueprints.

void SortByInitiative(TArray<MyActor*> &Actors)
{
  Actors.Sort([](const MyActor *A, const MyActor *B) -> bool
  {
    return A->InitiativeSet < B->InitiativeSet;
  }
}

Use > (greater than) instead if you want to go from large to low numbers.

This would be callable by your blueprint if you put the ‘BlueprintCallable’ tag in your UFUNCTION metadata. Make the function static and it’s callable from any blueprint.