Download

How to sort and re-arrange an array by attributes

I have an array of objects created by doing a “Get All Actors In Class” function. I would like to re-sort that array based on distance from the camera. Honestly, I’d like to do it on any parameter I can think of (say scale, X coordinate, exposed custom variable, etc). I’ve been banging my head at this for awhile, but can’t quite grasp the logic. There doesn’t seem to be a built in sorting function, so I have to brute force it and code the behavior by hand. I even looked up on Wikipedia the logic behind a basic sorting algorithm (http://en.wikipedia.org/wiki/Insertion_sort) but I can’t figure out how to translate that into Blueprint logic.

Any hints or nudges out there?

Dude, I’m sorry, I had to come by and post just to give you props on the name. Lol

As far as your question, I am not familiar with if you can sort arrays in Blueprints and you are probably right that you would have to possibly create a static function that takes a TArray<T>, creates a temp one in the function, resorts it and then passes it back. Are you able to program it or are you stuck with Blueprints?

If you are stuck to Blueprints, you would probably have two arrays, one that’s just a temporary one and one that holds the sorted content. After you get your array, run a ForEach loop on it and evaluate the distance (d = sqrt((x2 - x1)^2 + (y2 - y1)^2 + (z2 - z1)^2)), then add those items to the sorted array. That should work but if you can program in C++, that’ll be easier and save you time.

Hope this helps and awesome name bud!

I know right…I had to comment on his first post cause of it as well…

That’s how I’d go about it as well…ForEach the array and place them in another array setting the Index by the compared distances…You might be able to do this in just 1 array but this will already get complicated so I would make it as simple as possible and use a second array…I do not envy you for this task but if it has to be done then it has to be done…Good luck…

Either this thread came from the forum wipe abyss, or I have become Nostradamus and can see the future.

I ended up commenting on a similar post in the AnswerHub, and after asking for help I finally cracked it on my own. I cheated and just copied some code from Wikipedia on sorting algorithms (maybe it was C++? not sure) and “re-imagined” it with Blueprint layouts instead. It was definitely one of those problems that made me realize that Blueprints still require you to think and step through your problem like a coder sometimes to find a solution.

Relevant AnswerHub link for future thread readers: How can I sort items in array by properties? - UE4 AnswerHub