Page 1 of 1

Different sort of sort

Posted: Mon Oct 17, 2016 10:17 pm
by RossG
I have lines in a field...

H,2.1
R,1.2
B,4.2
L,3.1
O,7.7
E,3.4

I want to sort them in order R,B,H,L,O,E.

How can I sort this way?

Re: Different sort of sort

Posted: Tue Oct 18, 2016 8:03 pm
by jacque
You need a custom sort function for something like this. Assuming a field that contains the data:

Code: Select all

on customSort
  put fld 1 into tList -- you could use a variable here instead
  put "R,B,H,L,O,E" into tOrderList
  split tOrderList by comma
  sort lines of tList by sortIt(each,tOrderList)
  -- do something with the sorted list here
end customSort

function sortit tLine,tOrderList
  repeat for each key k in tOrderList
    if tOrderList[k] = item 1 of tLine then
      return k
    end if
  end repeat
end sortit

Re: Different sort of sort

Posted: Tue Oct 18, 2016 9:36 pm
by rkriesel
Hi, RossG.

You could sort the field using an array:

Code: Select all

repeat for each item k in "R,B,H,L,O,E"
  add 1 to i
  put i into a[ k ]
end repeat
sort fld 1 by a[ item 1 of each ]
-- Dick

Re: Different sort of sort

Posted: Tue Oct 18, 2016 10:04 pm
by [-hh]
This is an interesting problem:
What to do with lines, that have something else as a first item (missing data/empty, typo)?
Here is a variant that includes this aspect.

Code: Select all

local orderList = "R,B,H,L,O,E"
sort myVar numeric by itemoffset(item 1 of each, orderList)
[The 'numeric' is only needed in case you have more than 9 items in your orderList]

Re: Different sort of sort

Posted: Tue Oct 18, 2016 11:47 pm
by dunbarx
@ Jacque, Dick.

Nice.

@Hermann.

Really nice.

All three of these should be combined as three instances of a solution to a problem, in a lesson in their own right.

Craig

Re: Different sort of sort

Posted: Wed Oct 19, 2016 1:42 am
by RossG
dunbarx wrote:@ Jacque, Dick.

Nice.

@Hermann.

Really nice.

All three of these should be combined as three instances of a solution to a problem, in a lesson in their own right.

Craig
What I would have said if I hadn't been so admiring of these
solutions that I was left "speechless". Three cheers and a cigar to each. Thank you.