Message Boards Message Boards

0
|
6255 Views
|
4 Replies
|
3 Total Likes
View groups...
Share
Share this post:

Use Sort with Strings?

Posted 5 years ago

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

POSTED BY: Robert McHugh
4 Replies

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] &]
POSTED BY: Ilian Gachevski

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"}}
POSTED BY: Eric Smith

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"

POSTED BY: Ilian Gachevski

You were faster in responding than I was in editing my original post. I agree with you.

POSTED BY: Eric Smith
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract