Sorting arrays by size

Hi! I think this is a basic question, but I am struggling to find a quick solution. I have three arrays like so:

array_one = [1,2,3,4]
array_two = [1,2]
array_three = [1,2,3,4,5]

I would like to sort them by size and put them into a single array, like this:

arrays_sorted_by_size = [array_three, array_one, array_two]

I am toying with different ideas, but I have the impression I am writing way too much code for something apparently so simple. Any quick tips?

Thanks!

Assuming there aren’t too many performance requirements for this, and also assuming you’re going to need to do this more than once:

var src_list = [array_one, array_two, array_three]
var dst_list = []

func sort_by_size(a, b) -> bool:
    if a.size() < b.size():
        return true
    return false

func build_list() -> void:
    src_list.sort_custom(sort_by_size)
    for el in src_list:
        dst_list.append_list(el)

That basically puts all your small lists inside a bigger list where we can sort them by size with sort_custom(). Once we have that, we iterate over them, expanding them into dst_list.

edit: sort_custom(), not custom_sort()

3 Likes

Thanks very much for that. :slight_smile: I knew there had to be a simpler answer to what I was trying.