If I have a string array that looks like this:
array = ["STRING1", "STRING05", "STRING20", "STRING4", "STRING3"]
or
array = ["STRING: 1", "STRING: 05", "STRING: 20", "STRING: 4", "STRING: 3"]
How can I sort the array by the number in each string (descending)?
I know that If the array consisted of integers and not strings, I could use:
sort_by { |k, v| -k }
I've searched all around but can't come up with a solution
In Ruby, it is easy to sort an array with the sort() function. When called on an array, the sort() function returns a new array that is the sorted version of the original one.
You can use sort_by with a block, and one argument, to define one attribute for each object which is going to be used as the basis for sorting (array length, object attribute, index, etc.). The block should return an integer value which determines the position of the object in the sorted array.
To sort an array of strings in Java, we can use Arrays. sort() function.
Convert each element in the String array obtained in the previous step into an integer and store in into the integer array. The sort() method of the Arrays class accepts an array, sorts the contents of it in ascending order. Sort the integer array using this method.
The below would sort by the number in each string and not the string itself
array.sort_by { |x| x[/\d+/].to_i }
=> ["STRING: 1", "STRING: 2", "STRING: 3", "STRING: 4", "STRING: 5"]
descending order:
array.sort_by { |x| -(x[/\d+/].to_i) }
=> ["STRING: 5", "STRING: 4", "STRING: 3", "STRING: 2", "STRING: 1"]
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