Page 1 of 1

Custom/semantic sort?

Posted: Sun Apr 09, 2023 2:50 am
by stam
Hi all,
I need to sort text data by a semantic rather than alphabetical order. I'm sure it must be possible, but would be grateful for any pointers.

As an example, I need to sort data where some options in a key/column would be "Routine", "Urgent" and "2-week wait".
If I sort 'normally' I' get these back in the order "2-week wait", "Routine" and "Urgent"
The desired order is "2-week wait", "Urgent" and "Rountine".
Furthermore there may be different options included int the future, so can't hard-code a solution.

Very grateful for any suggestions,
Stam

Re: Custom/semantic sort?

Posted: Sun Apr 09, 2023 2:16 pm
by paul@researchware.com
So, assuming the data is a variable (tData) in a tab and cr delimited format, and colmn 4 (or item 4 say) is the sort column (i.e. "Routine", "Urgent" and "2-week wait"), you can use

set itemDel to tab -- set itemDel to tab
sort lines of tData by mySort(item 4 or each) -- mySort is a custom function to return the sort order
set itemDel to comma -- reset itemDel


function mySort tKey
local tSortOrder = "2-week wait,Urgent,Routine" -- list the values in the order you want them sorted, expand as needed
return itemOffset(tKey,tSortOrder) -- returns the item number (1,2 or 3) of the key and this is the order the lines will be sorted in
end mySort

Re: Custom/semantic sort?

Posted: Sun Apr 09, 2023 8:40 pm
by stam
paul@researchware.com wrote:
Sun Apr 09, 2023 2:16 pm
So, assuming the data is a variable (tData) in a tab and cr delimited format, and colmn 4 (or item 4 say) is the sort column (i.e. "Routine", "Urgent" and "2-week wait"), you can use

set itemDel to tab -- set itemDel to tab
sort lines of tData by mySort(item 4 or each) -- mySort is a custom function to return the sort order
set itemDel to comma -- reset itemDel


function mySort tKey
local tSortOrder = "2-week wait,Urgent,Routine" -- list the values in the order you want them sorted, expand as needed
return itemOffset(tKey,tSortOrder) -- returns the item number (1,2 or 3) of the key and this is the order the lines will be sorted in
end mySort
Thank Paul, very much appreciated.