"Last" Item (last Database #) Owned Won't Alphabetize (RMXP))

I copied this line from the Window_Armor to Window_Items



            #alphabetize snippet.
            @data.sort! {|x,y| x.name <=> y.name if x != nil and y != nil }


because I want my items to alphabetize when I open up the backpack. All items alphabetize, except the item owned with the highest database number (in my game it's 0052 in the database, and it will not alphabetize and shows up always at the end of the list.)


If I give the hero an item 0053 (in the database), then item 0052 successfully alphabetizes in the visible menu, but now 0053 shows up at the end of the list.


Is there a way to alphabetize ALL the items, or do I honestly have to give my hero a blank item to always have in their inventory so the real items will sort?

Surely there is some simple way to improve this code?
The code you use should throw an error if there is any nil elements inside the @data array, regardless of your nil checks.
At least it did for me when I tried it.

You should try something like this:
Code:
@data.sort! {|x,y| x.nil? || y.nil? ? -2 : x.name <=> y.name  }
This will leave the nil element at the last position (where it should be if your list got a nil element), but sorts all other items.

If this won't work, you will have to share the contents of the @data array, and the place where you actually sort the list.

You could also try this:
Code:
inc_nil = @data.nitems != @data.size
@data = @data.compact.sort! {|x,y| x.name <=> y.name }
@data << nil if inc_nil
But I don't know if this will work in XP or not.
This basically removes the nil element for the time of sorting, and puts it back after the sorting if the @data array contained a nil element before the sort.

I based my reply on assuming that the nil element breaks your sorting, but if it is not the cause, none of the above will work.

Original thread: https://forums.rpgmakerweb.com/threads/last-item-last-database-owned-wont-alphabetize-rmxp.74365/