The Sort command below provided an unexpected result.
Could someone describe how to modify this code to Sort based on the Strings in the 3rd column of the array?
Sort[{{a, 2, "az"}, {c, 1, "aa"}, {d, 3, "ba"}}, #1[[3]] < #2[[3]] &]
Result is: {{a, 2, “az”}, {c, 1, “aa”}, {d, 3, “ba”}}
Expected: {{c, 1, “aa”}, {a, 2, “az”}, {d, 3, “ba”}}
Documentation indicates that Sort orders strings like a dictionary, Sort documentation page
iliang
(Ilian Gachevski)
April 8, 2019, 4:21am
2
Less does not work with strings, as in e.g. "az" < "aa".
Try something like
Sort[{{a, 2, "az"}, {c, 1, "aa"}, {d, 3, "ba"}}, Order[#1[[3]], #2[[3]]] &]
or
SortBy[{{a, 2, "az"}, {c, 1, "aa"}, {d, 3, "ba"}}, Part[#, 3] &]
ericsmith
(Eric Smith)
April 9, 2019, 7:25pm
3
EDIT: I guess he is asking for sorting by part 3, so you’re right. A little simpler to use “Last”:
SortBy[{{a, 2, "az"}, {c, 1, "aa"}, {d, 3, "ba"}}, Last]
Looking at his expected results, it looks like he wants to sort by Part[#,2]&
SortBy[{{a, 2, "az"}, {c, 1, "aa"}, {d, 3, "ba"}}, Part[#, 2] &]
Returns
{{c, 1, "aa"}, {a, 2, "az"}, {d, 3, "ba"}}
iliang
(Ilian Gachevski)
April 9, 2019, 7:28pm
4
Looking at his expected results, it looks like he wants to sort by Part[#,2]&
That is not how I read “Sort based on the Strings in the 3rd column”
ericsmith
(Eric Smith)
April 9, 2019, 7:29pm
5
You were faster in responding than I was in editing my original post. I agree with you.