+3 votes

I use Godot 3.

Lets's say I have the following array and it is structured like this....
slots[0] = ""
slots{1] = 11
slots[2] = 1
slots[3] = ""
slots[4] = 4

But I need some type of code that ill actrually sort the array structure so it ends up like this instead...
slots[0] = 1
slots{1] = 4
slots[2] = 11
slots[3] = ""
slots[4] = ""

Please help?

in Engine by (47 points)

1 Answer

+8 votes
func _ready():
    var arr = ["",11,1,"",4]
    arr.sort_custom(self, "customComparison")
    print (arr)

func customComparison(a, b):
    if typeof(a) != typeof(b):
        return typeof(a) < typeof(b)
        return a < b

This code depends on integer values assigned to types. Currently int is 2 and string is 4. If it ever changes, which is doubtful, results can be different.

And here's code that allows to specify order of types in sorting:

const TypeOrder = [TYPE_STRING, TYPE_INT]

func customComparison2(a, b):
    if typeof(a) != typeof(b):
        if typeof(a) in TypeOrder and typeof(b) in TypeOrder:
            return TypeOrder.find( typeof(a) ) < TypeOrder.find( typeof(b) )
            return typeof(a) < typeof(b)
        return a < b

In this case strings are before integers.

by (2,300 points)
edited by

Arrays are sorted in place.


turns arr into a sorted array.

it doesn't return the array so you don't need to do

newarr = arr.sort()

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.