Sorting by item ... of each and item ... of each

Mark Waddingham mark at livecode.com
Sun Sep 3 05:49:30 EDT 2023


On 2023-09-03 10:26, panagiotis m via use-livecode wrote:
> Hello Matthias,
> 
> I do not think that the syntax "sort <container> by sortKey1 and 
> sortKey2"
> is supported

Heh technically it 'is' - and does do something but it won't be what you 
expected...

So the syntax for sort in this case is:

    sort <container> by <expression>

This works by iterating over the elements in <container>, passing each 
through the expression to generate a sort key list, sorting that list 
and then reordering the original list.

Expressions can contain the boolean 'and' operator, so:

    sort <container> by X and Y

Means that the sort key is evaluated as 'X and Y' for each element - 
meaning sort ends up sorting a list of 'true' and 'false' values.

As Panos says, if you want to sort by separate fields with decreasing 
priority you need to do multiple sorts from least priority to most - 
this works because 'sort' is stable (if two elements compare the same, 
then the order of them in the output list is the same as the first).

The alternative is to work out a sort expression which combines the two 
parts of the element you want to sort so that the sort keys sort in that 
order. This can be quite tricky, but (for example) - let's say your 
container has elements of the form:

    <section-number>,<sub-section-number>

So you want things in the 'obvious' sorted order - then you could use:

    sort tSections ascending text by format("%08d%08d", item 1 of each, 
item 2 of each)

Here the sortkey is defined so that the text sort of the sort keys is 
that same as sorting first by sub-section number and then by section 
number.

Warmest Regards,

Mark.

-- 
Mark Waddingham ~ mark at livecode.com ~ http://www.livecode.com/
LiveCode: Build Amazing Things



More information about the use-livecode mailing list