applescript: get item number of list item
Posted by philastokes

One of the annoying ‘missing features’ in AppleScript is the lack of any way to get the item number of an item in a list.
Fortunately, since Cocoa does of course include an ‘indexOfObject’ function, we can leverage Cocoa in our AppleScript to write a nice little handler (you could add this to my list and string handlers library I posted here or just add it directly in your own scripts).
First, make sure your script or library already has two lines like these to import the Foundation framework and declare an NSArray:
use framework "Foundation"
property NSArray : a reference to current application's NSArray
Then after that add the handler:
on getIndexOfItem:anItem inList:aListset anArray to NSArray's arrayWithArray:aListset ind to ((anArray's indexOfObject:anItem) as number) + 1 # see note belowif ind is greater than (count of aList) thendisplay dialog "Item '" & anItem & "' not found in list." buttons "OK" default button "OK" with icon 2 with title "Error"return 0elsereturn indend ifend getIndexOfItem:inList:
You can now call the code like this:
# exampleset thisList to {"I", "see", "a", "red", "door", "and", "I", "want", "to", "paint", "it", "black"}set aNum to its getIndexOfItem:"paint" inList:thisList(* Result --> 10 *)if aNum is not 0 then-- do somethingend if
# Note: Remember AppleScript lists are indexed from 1, unlike Cocoa arrays which start at index 0.
Enjoy! 🙂
Share this:
Related
About philastokes
Independent Software Developer, Technical Writer and Researcher at SentinelOne. Explaining the unexplainable with images, video and text. Scripting anything imaginable in AppleScript, Bash, Python and Swift.Posted on August 9, 2016, in AppleScript, Cocoa and tagged list. Bookmark the permalink. Leave a comment.

Leave a comment
Comments 0