What is the more idiomatic way to sort a vector of strings by char?
Example:
Input:
["3r", "2n", "2s", "7r", "1s", "1s", "6r", "1s", "1n", "1n", "5n", "9n", "3r"]
Desired output:
["1n", "1n", "2n", "5n", "9n, "3r", "3r", "6r", "7r", "1s", "1s", "1s", "2s"]
First they need to be sorted on the second char so they are grouped together, after that sorted by first char.
I tried a bunch of things with .filter
and .sort_by
but was not successful.
If your strings are always two characters long, and you always want to sort them by the second character first, you can use .sort_by
with a comparator which looks at the strings in reverse:
let mut input = vec!("3r", "2n", "2s", "7r", "1s", "1s", "6r", "1s", "1n", "1n", "5n", "9n", "3r");
input.sort_by(|a, b| a.chars().rev().cmp(b.chars().rev()));
let expected = vec!("1n", "1n", "2n", "5n", "9n", "3r", "3r", "6r", "7r", "1s", "1s", "1s", "2s");
assert!(input == expected);