I have an array of strings like this:
["Brazil (62)", "PalestinianTerritoryOccupied (6)", "Macedonia (2)", "Germany (6)"]
I want to sort them by the highest value but it's got me stumped. I've tried all sorts of weird, wonderful (and useless) things like:
cont.sort! { |it| it.scan(/\d+/).to_s.to_i}
The sort() method allows you to sort elements of an array in place. Besides returning the sorted array, the sort() method changes the positions of the elements in the original array. By default, the sort() method sorts the array elements in ascending order with the smallest value first and largest value last.
Example 1: Sort Array by Property NameThe sort() method sorts its elements according to the values returned by a custom sort function ( compareName in this case). Here, The property names are changed to uppercase using the toUpperCase() method. If comparing two names results in 1, then their order is changed.
Example: Sort an Array in Java in Ascending Order Then, you should use the Arrays. sort() method to sort it. That's how you can sort an array in Java in ascending order using the Arrays. sort() method.
To sort an array of objects, you use the sort() method and provide a comparison function that determines the order of objects.
sort_by {|e| e[/\d+/].to_i }.reverse
should do the trick. You can write this one in a more efficient and elegant way (see comments), like in the following:
sort_by {|e| -e[/\d+/].to_i }
Note the -
.
Using sort you can do:
sort {|a, b| b[/\d+/].to_i <=> a[/\d+/].to_i }
EDIT
String#[] has been suggested in the comments.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With