Sort Array of Struct Values

Let’s assume you have a struct defined with some property you want to sort by…

struct my_struct
float my_property = 0;

void randomize_yourself()
float random_value = nrandom();
this.my_property = random_value;

During some process you end up having an array of that struct

my_struct a;
my_struct b;
my_struct c;


my_struct my_objects[] = {a, b, c};

Now to sort the array by a property

float values[];
foreach(my_struct my_object; my_objects)
push(values, my_object.my_property);

int ordering[] = argsort(values);

my_struct temp[];
foreach(int i; ordering)
push(temp, my_objects[i]);

my_objects = temp;
// my_objects array is now sorted by my_struct.my_property values

The trick is to use argsort which gives you an array of indexes to sort by.

About the Author

Martin Karlsson

Technical Leadership | Pipelines | Houdini | VEX | Maya | Python | Photogrammetry