How to sort Array?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By BigDC

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?

:bust_in_silhouette: Reply From: hilfazer
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.

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()

ryanscott | 2021-08-23 01:48