2D array sorting error

Godot Version

v4.1.3.stable.official.f06b6836a

Question

Hello, I am trying to sort this 2d array by the float value (a time). The first element is a name.

This is the line I use:

sorted_entered_swimmers_times = entered_swimmers_times.sort_custom(sort_ascending_by_time)

But I don’t understand why this sort_custom returns “void”…

The array I use is declared like this:

	var swimmers_to_enter = []
	for swimmer in all_swimmers:
		swimmers_to_enter.append([swimmer.name_swimmer,swimmer.time])
	var test_event_object = SwimEvent.new(event_50_freestyle, swimmers_to_enter)

Does it work if you add a type hint for the return value?

func sort_ascending_by_time(a: Array, b: Array) -> bool:
    return a[1] < b[1]

Edit: Actually, the problem is that you’re trying to do a non-sensical assignment. sort_custom() sorts the array instead of returning a new array. If you want to keep the unsorted array, you need to duplicate it before sorting.

sorted_entered_swimmers_times = entered_swimmers_times.duplicate()
sorted_entered_swimmers_times.sort_custom(sort_ascending_by_time)

This works thank you!!

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.