#1628 Sorting Numbers that are in Strs

yliu Tue 30 Aug 2011

This probably is asking for too much but, could List.sort account for numerical order as well.

[1,2,3,4,5,6,7,8,9,10,11,12].sort

sorts fine, but

["1","2","3","4","5","6","7","8","9","10","11","12"]

will sort to,

[1,11,12,2,3,4,5,6,7,8,9]

which makes complete sense when you think about it in the Str context. Still seeing lists that sort to..

[obj_1, obj_10, obj_11, obj_2, obj_3, obj_4, obj_5, obj_6, obj_7, obj_8, obj_9]

..isn't really what you expect to happen when you add a number to the str name of an object. Would this be a bad modification for fantom's List.sort method? Or, is there a reason behind having List.sort work in this fashion?

brian Tue 30 Aug 2011

Well comparison of Ints and Strs is extremely well defined and I don't think we should want to touch default ordering of char code points (or the way localeCompare works). I think you just need to use a custom sorter function. I have in the past used custom sorting functions for files that might take numbers into account like that, but it is very difficult to do it in a general purpose. For example what might be separators or is there file extensions you strip off beforehand, etc.

ttmrichter Wed 31 Aug 2011

A quick and simple fix is to prepend 0 to numbers as needed to make them all the same length. That way you'll have "01", "02" and so on which will sort fine.

Login or Signup to reply.