How to Sort Numbers with AppleScriptObjC

Hey Folks,

How can you sort a list of numbers using AppleScriptObjC without making the list unique?

TIA.

-Chris

----------------------------------------------------------------

use AppleScript version "2.4" -- 10.10 or later
use framework "Foundation"
use scripting additions

set theList to {2, 20, 3, 1, 21, 21}
-- Make unique set
tell current application's NSSet to set theSet to setWithArray_(theList)
-- Define sorting
tell current application's NSSortDescriptor to set theDescriptor to sortDescriptorWithKey_ascending_(missing value, true)
-- Sort
set sortedList to (theSet's sortedArrayUsingDescriptors:{theDescriptor}) as list

return sortedList

----------------------------------------------------------------

Make an array rather than a set. You also don’t need a sort descriptor for a basic sort:

use AppleScript version "2.4" -- 10.10 or later
use framework "Foundation"
use scripting additions

set theList to {2, 20, 3, 1, 21, 21}
set theArray to current application's NSArray's arrayWithArray:theList
set sortedList to (theArray's sortedArrayUsingSelector:"compare:") as list

return sortedList
1 Like

Hey Shane,

Thanks. I was testing with nearly that exact code last night and having problems that don’t seem to be extant in the light of today.

Mebbe just too tired, 'cause my test code is working perfectly well at the moment.

<shrug>

In any case – is there a descending sort selector? Or is reverse of the way to go?

-Chris

Use reverse of, or a sort descriptor as in your posted script. There’s no dedicated method. An array can be reversed in ASObjC:

set sortedList to (theArray's sortedArrayUsingSelector:"compare:")'s reverseObjectEnumerator()'s allObjects() as list

But it’s a bit of a mouthful, and vaguely indirect.

1 Like