Guides and Sample Code

Developer

Mac Automation Scripting Guide

On This Page

Manipulating Lists of Items

In scripting, a list—typically referred to as an array in JavaScript—is a an ordered collection of values that’s stored in a single object. A script can loop through the items of a list in order to process the items individually. There are many other tasks scripts commonly performed with lists, such as joining and sorting, which usually require custom scripting.

Looping through a List

Listing 21-1 and Listing 21-2 show how to incrementally loop through a list. In these examples, a variable—a in AppleScript and i in JavaScript—represents an integer value from 1 through the number of items in the list. Each loop causes this variable value to increase, and you can use the increment variable to target a specific list item.

APPLESCRIPT

Open in Script Editor

Listing 21-1AppleScript: Incrementally looping through items in a list
  1. set theList to {"Sal", "Ben", "David", "Chris"}
  2. repeat with a from 1 to length of theList
  3. set theCurrentListItem to item a of theList
  4. -- Process the current list item
  5. display dialog theCurrentListItem & " is item " & a & " in the list."
  6. end repeat

JAVASCRIPT

Open in Script Editor

Listing 21-2JavaScript: Incrementally looping through items in an array
  1. var app = Application.currentApplication()
  2. app.includeStandardAdditions = true
  3. var array = ["Sal", "Ben", "David", "Chris"]
  4. var arrayLength = array.length
  5. for (var i = 0; i < arrayLength; i++) {
  6. var currentArrayItem = array[i]
  7. // Process the current array item
  8. app.displayDialog(`${currentArrayItem} is item ${i + 1} in the array.`)
  9. }

A script can also loop through a list of items more directly by dynamically assigning a list item to a variable. In Listing 21-3 and Listing 21-4, a variable—theCurrentListItem in AppleScript and currentArrayItem in JavaScript—represents the item matching the current loop.

APPLESCRIPT

Open in Script Editor

Listing 21-3AppleScript: Directly looping through items in a list
  1. set theList to {"Sal", "Ben", "David", "Chris"}
  2. repeat with theCurrentListItem in theList
  3. -- Process the current list item
  4. display dialog theCurrentListItem & " is an item in the list."
  5. end repeat

JAVASCRIPT

Open in Script Editor

Listing 21-4JavaScript: Directly looping through items in an array
  1. var app = Application.currentApplication()
  2. app.includeStandardAdditions = true
  3. var array = ["Sal", "Ben", "David", "Chris"]
  4. var arrayLength = array.length
  5. for (var currentArrayItem of array) {
  6. // Process the current array item
  7. app.displayDialog(`${currentArrayItem} is an item in the array.`)
  8. }

Converting a List to a String

The handler in Listing 21-5 joins a list of strings together in AppleScript, separating them by a specific delimiter.

APPLESCRIPT

Open in Script Editor

Listing 21-5AppleScript: Handler that converts a list of strings into a single string
  1. on convertListToString(theList, theDelimiter)
  2. set AppleScript's text item delimiters to theDelimiter
  3. set theString to theList as string
  4. set AppleScript's text item delimiters to ""
  5. return theString
  6. end convertListToString

Listing 21-6 shows how to call the handler in Listing 21-5.

APPLESCRIPT

Open in Script Editor

Listing 21-6AppleScript: Calling a handler to convert a list of strings into a single string
  1. set theList to {"The", "quick", "brown", "fox", "jumps", "over", "a", "lazy", "dog."}
  2. convertListToString(theList, space)
  3. --> Result: "The quick brown fox jumps over a lazy dog."

In JavaScript, custom scripting isn’t required to perform this operation. The Array object has a join() method, which can be called to merge a list of items together, as shown in Listing 21-7.

JAVASCRIPT

Open in Script Editor

Listing 21-7JavaScript: Calling a function to convert an array of strings into a single string
  1. var array = ["The", "quick", "brown", "fox", "jumps", "over", "a", "lazy", "dog."]
  2. var array.join(" ")
  3. // Result: "The quick brown fox jumps over a lazy dog."

Counting the Items in a List

Listing 21-10 and Listing 21-11 show how to get the number of items in a list.

APPLESCRIPT

Open in Script Editor

Listing 21-10AppleScript: Get the count of the items in a list
  1. set theList to {"Apple Watch", "iMac", "iPhone", "MacBook Pro"}
  2. length of theList
  3. --> Result: 4

JAVASCRIPT

Open in Script Editor

Listing 21-11JavaScript: Get the count of the items in an array
  1. var array = ["Apple Watch", "iMac", "iPhone", "MacBook Pro"]
  2. array.length
  3. // Result: 4

Counting the Occurrences of an Item in a List

The handlers in Listing 21-12 and Listing 21-13 count how many times an item appears in a list.

APPLESCRIPT

Open in Script Editor

Listing 21-12AppleScript: Handler that counts the number of times an item appears in a list
  1. on countInstancesOfItemInList(theList, theItem)
  2. set theCount to 0
  3. repeat with a from 1 to count of theList
  4. if item a of theList is theItem then
  5. set theCount to theCount + 1
  6. end if
  7. end repeat
  8. return theCount
  9. end countInstancesOfItemInList

JAVASCRIPT

Open in Script Editor

Listing 21-13JavaScript: Function that counts the number of times an item appears in an array
  1. function countInstancesOfItemInArray(array, item) {
  2. var count = 0
  3. for (var element of array) {
  4. if (element === item) {
  5. count++
  6. }
  7. }
  8. return count
  9. }

Listing 21-14 and Listing 21-15 show how to call the handlers in Listing 21-12 and Listing 21-13.

APPLESCRIPT

Open in Script Editor

Listing 21-14AppleScript: Calling a handler to count the number of times an item appears in a list
  1. set theList to {"Sal", "Jen", "Ben", "David", "Chris", "Jen"}
  2. countInstancesOfItemInList(theList, "Jen")
  3. --> Result: 2

JAVASCRIPT

Open in Script Editor

Listing 21-15JavaScript: Calling a function to count the number of times an item appears in an array
  1. var array = ["Sal", "Jen", "Ben", "David", "Chris", "Jen"]
  2. countInstancesOfItemInArray(array, "Jen")
  3. // Result: 2

Determining if a List Contains a Specific Item

Listing 21-16 and Listing 21-17 return a true or false value, indicating the presence of an item in a list.

APPLESCRIPT

Open in Script Editor

Listing 21-16AppleScript: Check for the existence of an item in a list
  1. set theList to {"Sal", "Ben", "David", "Chris"}
  2. theList contains "Lizzie"
  3. --> false

JAVASCRIPT

Open in Script Editor

Listing 21-17JavaScript: Check for the existence of an item in an array
  1. var array = ["Sal", "Ben", "David", "Chris"]
  2. array.includes("Lizzie")
  3. // Result: false

Listing 21-18 and Listing 21-19 demonstrate how to add an item to a list only if the list doesn’t already contain the item.

APPLESCRIPT

Open in Script Editor

Listing 21-18AppleScript: Add an item to a list only if the list doesn’t contain the item
  1. set theList to {"Sal", "Ben", "David", "Chris"}
  2. if theList does not contain "Jen" then
  3. set end of theList to "Jen"
  4. end if
  5. return theList
  6. --> Result: {"Sal", "Ben", "David", "Chris", "Jen"}

JAVASCRIPT

Open in Script Editor

Listing 21-19JavaScript: Add an item to an array only if the array doesn’t contain the item
  1. var array = ["Sal", "Ben", "David", "Chris"]
  2. if (!array.includes("Jen")) {
  3. array.push("Jen")
  4. }
  5. array
  6. // Result: ["Sal", "Ben", "David", "Chris", "Jen"]

Determining the Position of an Item in a List

The handler in Listing 21-20 determines the position of an item the first time it appears in a list.

APPLESCRIPT

Open in Script Editor

Listing 21-20AppleScript: Handler that determines the position of an item in a list
  1. on getPositionOfItemInList(theItem, theList)
  2. repeat with a from 1 to count of theList
  3. if item a of theList is theItem then return a
  4. end repeat
  5. return 0
  6. end getPositionOfItemInList

Listing 21-21 shows how to call the handler in Listing 21-20. In AppleScript, list item positions start at 1—the first item in a list has a position of 1.

APPLESCRIPT

Open in Script Editor

Listing 21-21AppleScript: Calling a handler to determine the position of an item in a list
  1. set theList to {"Sal", "Ben", "David", "Chris", "Jen", "Lizzie", "Maddie", "Lillie"}
  2. getPositionOfItemInList("Maddie", theList)
  3. --> Result: 7

In JavaScript, the indexOf() method of the Array object can be called to determine the position of an item in an array, as shown in Listing 21-22. In JavaScript, array item positions start at 0—the first item in an array has an index of 0.

JAVASCRIPT

Open in Script Editor

Listing 21-22JavaScript: Determine the position of an item in an array
  1. var array = ["Sal", "Ben", "David", "Chris", "Jen", "Lizzie", "Maddie", "Lillie]
  2. array.indexOf("Maddie")
  3. // Result: 6

The getPositionOfItemInList() AppleScript handler and indexOf() JavaScript method can be used to cross-reference data between corresponding lists. In Listing 21-23 and Listing 21-24, a person is located in a list by name. Next, the person’s phone extension is located in a corresponding list.

APPLESCRIPT

Open in Script Editor

Listing 21-23AppleScript: Using cross-referencing to locate an item in a list based on the position of an item in another list
  1. set theNames to {"Sal", "Ben", "David", "Chris", "Jen", "Lizzie", "Maddie", "Lillie"}
  2. set theExtensions to {"x1111", "x2222", "x3333", "x4444", "x5555", "x6666", "x7777", "x8888"}}
  3. set thePerson to choose from list theNames with prompt "Choose a person:"
  4. if thePerson is false then error number -128
  5. set theExtension to item (getPositionOfItemInList((thePerson as string), theNames)) of theExtensions
  6. display dialog "The phone extension for " & thePerson & " is " & theExtension & "."

JAVASCRIPT

Open in Script Editor

Listing 21-24JavaScript: Using cross-referencing to locate an item in an array based on the position of an item in another array
  1. var app = Application.currentApplication()
  2. app.includeStandardAdditions = true
  3. var names = ["Sal", "Ben", "David", "Chris", "Jen", "Lizzie", "Maddie", "Lillie"]
  4. var extensions = ["x1111", "x2222", "x3333", "x4444", "x5555", "x6666", "x7777", "x8888"]
  5. var people = app.chooseFromList(names, {withPrompt: "Choose a person:"})
  6. if (!people) {
  7. throw new Error(-128)
  8. }
  9. var person = people[0]
  10. var index = names.indexOf(person)
  11. console.log(index)
  12. var extension = extensions[index]
  13. app.displayDialog(`The phone extension for ${person} is ${extension}.`)

Determining Multiple Positions of an Item in a List

The handlers in Listing 21-25 and Listing 21-26 determine every position of an item in a list.

APPLESCRIPT

Open in Script Editor

Listing 21-25AppleScript: Handler that determines every position of an item in a list
  1. on getPositionsOfItemInList(theItem, theList, listFirstPositionOnly)
  2. set thePositions to {}
  3. repeat with a from 1 to length of theList
  4. if item a of theList is theItem then
  5. if listFirstPositionOnly = true then return a
  6. set end of thePositions to a
  7. end if
  8. end repeat
  9. if listFirstPositionOnly is true and thePositions = {} then return 0
  10. return thePositions
  11. end getPositionsOfItemInList

JAVASCRIPT

Open in Script Editor

Listing 21-26JavaScript: Function that determines every position of an item in an array
  1. function getPositionsOfItemInArray(item, array, firstPositionOnly) {
  2. if (firstPositionOnly) {
  3. return array.indexOf(item)
  4. }
  5. var indexes = []
  6. for (var index = 0; index < array.length; index++) {
  7. var element = array[index]
  8. if (element === item) {
  9. indexes.push(index)
  10. }
  11. }
  12. return indexes
  13. }

Listing 21-27 and Listing 21-28 show how to call the handlers in Listing 21-25 and Listing 21-26.

APPLESCRIPT

Open in Script Editor

Listing 21-27AppleScript: Calling a handler to determine every position of an item in a list
  1. set theList to {"Sal", "Ben", "Jen", "David", "Chris", "Lizzie", "Maddie", "Jen", "Lillie"}
  2. getPositionsOfItemInList("Jen", theList, false)
  3. --> Result: {3, 8}

JAVASCRIPT

Open in Script Editor

Listing 21-28JavaScript: Calling a function to determine every position of an item in an array
  1. var array = ["Sal", "Ben", "Jen", "David", "Chris", "Lizzie", "Maddie", "Jen", "Lillie"]
  2. getPositionsOfItemInArray("Jen", array, false)
  3. // Result: [2, 7]

Finding the Highest Numeric Value in a List

The handlers in Listing 21-29 and Listing 21-30 determine the highest numeric value in a list of items. The passed list can contain non-numeric data as well as lists within lists.

APPLESCRIPT

Open in Script Editor

Listing 21-29AppleScript: Handler that determines the highest numeric value in a list of items
  1. on getHighestNumberInList(theList)
  2. set theHighestNumber to false
  3. repeat with a from 1 to count of theList
  4. set theCurrentItem to item a of theList
  5. set theClass to class of theCurrentItem
  6. if theClass is in {integer, real} then
  7. if theHighestNumber is "" then
  8. set theHighestNumber to theCurrentItem
  9. else if theCurrentItem is greater than theHighestNumber then
  10. set theHighestNumber to item a of theList
  11. end if
  12. else if theClass is list then
  13. set theHighValue to getHighestNumberInList(theCurrentItem)
  14. if theHighValue is greater than theHighestNumber then
  15. set theHighestNumber to theHighValue
  16. end if
  17. end if
  18. end repeat
  19. return theHighestNumber
  20. end getHighestNumberInList

JAVASCRIPT

Open in Script Editor

Listing 21-30JavaScript: Function that determines the highest numeric value in a list of items
  1. function getHighestNumberInList(list) {
  2. var highestNumber = undefined
  3. for (var item of list) {
  4. var number = undefined
  5. if (item.constructor === Number) {
  6. number = item
  7. }
  8. else if (item.constructor === Array) {
  9. number = getHighestNumberInList(item)
  10. }
  11. if (number != undefined && (highestNumber === undefined || number > highestNumber)) {
  12. highestNumber = number
  13. }
  14. }
  15. return highestNumber
  16. }

Listing 21-31 and Listing 21-32 show how to call the handlers in Listing 21-29 and Listing 21-30 for a list containing a mixture of numbers and strings.

APPLESCRIPT

Open in Script Editor

Listing 21-31AppleScript: Calling a handler to determine the highest numeric value in a list of numbers and strings
  1. getHighestNumberInList({-3.25, 23, 2345, "sid", 3, 67})
  2. --> Result: 2345

JAVASCRIPT

Open in Script Editor

Listing 21-32JavaScript: Calling a function to determine the highest numeric value in a list of numbers and strings
  1. getHighestNumberInList([-3.25, 23, 2345, "sid", 3, 67])
  2. // Result: 2345

Listing 21-33 and Listing 21-34 show how to call the handlers in Listing 21-29 and Listing 21-30 for a list containing a mixture of numbers, strings, booleans, and lists.

APPLESCRIPT

Open in Script Editor

Listing 21-33AppleScript: Calling a handler to determine the highest numeric value in a list of different value types
  1. getHighestNumberInList({-3.25, 23, {23, 78695, "bob"}, 2345, true, "sid", 3, 67})
  2. --> Result: 78695

JAVASCRIPT

Open in Script Editor

Listing 21-34JavaScript: Calling a function to determine the highest numeric value in a list of different value types
  1. getHighestNumberInList([-3.25, 23, [23, 78695, "bob"], 2345, true, "sid", 3, 67])
  2. // Result: 78695

Listing 21-35 and Listing 21-36 show how to call the handlers in Listing 21-29 and Listing 21-30 for a list containing only strings.

APPLESCRIPT

Open in Script Editor

Listing 21-35AppleScript: Calling a handler to determine the highest numeric value in a list of strings
  1. getHighestNumberInList({"this", "list", "contains", "only", "text"})
  2. --> Result: false

JAVASCRIPT

Open in Script Editor

Listing 21-36JavaScript: Calling a function to determine the highest numeric value in a list of strings
  1. getHighestNumberInList(["this", "list", "contains", "only", "text"])
  2. // Result: undefined

Finding the Lowest Numeric Value in a List

The handlers in Listing 21-37 and Listing 21-38 determines the lowest numeric value in a list of items. The passed list can contain non-numeric data as well as lists within lists.

APPLESCRIPT

Open in Script Editor

Listing 21-37AppleScript: Handler that determines the lowest numeric value in a list of items
  1. on getLowestNumberInList(theList)
  2. set theLowestNumber to false
  3. repeat with a from 1 to count of theList
  4. set theCurrentItem to item a of theList
  5. set theClass to class of theCurrentItem
  6. if theClass is in {integer, real} then
  7. if theLowestNumber is "" then
  8. set theLowestNumber to theCurrentItem
  9. else if theCurrentItem is less than theLowestNumber then
  10. set theLowestNumber to item a of theList
  11. end if
  12. else if theClass is list then
  13. set theLowValue to getLowestNumberInList(theCurrentItem)
  14. if theLowValue is less than theLowestNumber then
  15. set theLowestNumber to theLowValue
  16. end if
  17. end if
  18. end repeat
  19. return theLowestNumber
  20. end getLowestNumberInList

JAVASCRIPT

Open in Script Editor

Listing 21-38JavaScript: Function that determines the lowest numeric value in a list of items
  1. function getLowestNumberInList(list) {
  2. var lowestNumber = undefined
  3. for (var item of list) {
  4. var number = undefined
  5. if (item.constructor === Number) {
  6. number = item
  7. }
  8. else if (item.constructor === Array) {
  9. number = getLowestNumberInList(item)
  10. }
  11. if (number != undefined && (lowestNumber === undefined || number < lowestNumber)) {
  12. lowestNumber = number
  13. }
  14. }
  15. return lowestNumber
  16. }

Listing 21-39 and Listing 21-40 show how to call the handlers in Listing 21-37 and Listing 21-38 for a list containing a mixture of numbers and strings.

APPLESCRIPT

Open in Script Editor

Listing 21-39AppleScript: Calling a handler to determine the lowest numeric value in a list of numbers and strings
  1. getLowestNumberInList({-3.25, 23, 2345, "sid", 3, 67})
  2. --> Result: -3.25

JAVASCRIPT

Open in Script Editor

Listing 21-40JavaScript: Calling a function to determine the lowest numeric value in a list of strings
  1. getLowestNumberInList([-3.25, 23, 2345, "sid", 3, 67])
  2. // Result: -3.25

Listing 21-41 and Listing 21-42 show how to call the handlers in Listing 21-37 and Listing 21-38 for a list containing a mixture of numbers, strings, booleans, and lists.

APPLESCRIPT

Open in Script Editor

Listing 21-41AppleScript: Calling a handler to determine the lowest numeric value in a list of different value types
  1. getLowestNumberInList({-3.25, 23, {-22, 78695, "Sal"}, 2345, true, "sid", 3, 67})
  2. --> Result: -22

JAVASCRIPT

Open in Script Editor

Listing 21-42JavaScript: Calling a function to determine the lowest numeric value in a list of different value types
  1. getLowestNumberInList([-3.25, 23, [-22, 78695, "bob"], 2345, true, "sid", 3, 67])
  2. // Result: -22

Listing 21-43 and Listing 21-44 show how to call the handlers in Listing 21-37 and Listing 21-38 for a list containing only strings.

APPLESCRIPT

Open in Script Editor

Listing 21-43AppleScript: Calling a handler to determine the lowest numeric value in a list of strings
  1. getLowestNumberInList({"this", "list", "contains", "only", "text"})
  2. --> Result: false

JAVASCRIPT

Open in Script Editor

Listing 21-44JavaScript: Calling a function to determine the lowest numeric value in a list of strings
  1. getLowestNumberInList(["this", "list", "contains", "only", "text"])
  2. // Result: undefined

Inserting Items into a List

The handlers in Listing 21-45 and Listing 21-46 insert an item into a list. Provide the item to insert, the list, and the position where the item should be inserted. Note that position can be specified in relation to the end of the list by using a negative number.

APPLESCRIPT

Open in Script Editor

Listing 21-45AppleScript: Handler that inserts an item into a list
  1. on insertItemInList(theItem, theList, thePosition)
  2. set theListCount to length of theList
  3. if thePosition is 0 then
  4. return false
  5. else if thePosition is less than 0 then
  6. if (thePosition * -1) is greater than theListCount + 1 then return false
  7. else
  8. if thePosition is greater than theListCount + 1 then return false
  9. end if
  10. if thePosition is less than 0 then
  11. if (thePosition * -1) is theListCount + 1 then
  12. set beginning of theList to theItem
  13. else
  14. set theList to reverse of theList
  15. set thePosition to (thePosition * -1)
  16. if thePosition is 1 then
  17. set beginning of theList to theItem
  18. else if thePosition is (theListCount + 1) then
  19. set end of theList to theItem
  20. else
  21. set theList to (items 1 thru (thePosition - 1) of theList) & theItem & (items thePosition thru -1 of theList)
  22. end if
  23. set theList to reverse of theList
  24. end if
  25. else
  26. if thePosition is 1 then
  27. set beginning of theList to theItem
  28. else if thePosition is (theListCount + 1) then
  29. set end of theList to theItem
  30. else
  31. set theList to (items 1 thru (thePosition - 1) of theList) & theItem & (items thePosition thru -1 of theList)
  32. end if
  33. end if
  34. return theList
  35. end insertItemInList

JAVASCRIPT

Open in Script Editor

Listing 21-46JavaScript: Function that inserts an item into an array
  1. function insertItemInArray(item, array, position) {
  2. var arrayCount = array.length
  3. if (Math.abs(position) > arrayCount) {
  4. return false
  5. }
  6. else if (position === 0) {
  7. array.unshift(item)
  8. }
  9. else if (position < arrayCount) {
  10. array.splice(position, 0, item)
  11. }
  12. else {
  13. array.push(item)
  14. }
  15. return array
  16. }

Listing 21-47 and Listing 21-48 show how to call the handlers in Listing 21-45 and Listing 21-46 to insert a single item into a list at a specific position.

APPLESCRIPT

Open in Script Editor

Listing 21-47AppleScript: Calling a handler to insert a single item at a specific position in a list
  1. set theList to {"Sal", "Ben", "David", "Chris"}
  2. insertItemInList("Jen", theList, 3)
  3. --> Result: {"Sal", "Ben", "Jen", "David", "Chris"}

JAVASCRIPT

Open in Script Editor

Listing 21-48JavaScript: Calling a function to insert a single item at a specific position in an array
  1. var array = ["Sal", "Ben", "David", "Chris"]
  2. array = insertItemInArray("Jen", array, 2)
  3. // Result = ["Sal", "Ben", "Jen", "David", "Chris"]

Listing 21-49 and Listing 21-50 show how to call the handlers in Listing 21-45 and Listing 21-46 to insert multiple items into a list at a specific position.

APPLESCRIPT

Open in Script Editor

Listing 21-49AppleScript: Calling a handler to insert multiple items at a specific position in a list
  1. set theList to {"Sal", "Ben", "David", "Chris"}
  2. insertItemInList({"Lizzie", "Maddie", "Lillie"}, theList, 3)
  3. --> Result: {"Sal", "Ben", "Lizzie", "Maddie", "Lillie", "David", "Chris"}

JAVASCRIPT

Open in Script Editor

Listing 21-50JavaScript: Calling a function to insert multiple items at a specific position in an array
  1. var array = ["Sal", "Ben", "David", "Chris"]
  2. var items = ["Lizzie", "Maddie", "Lillie"]
  3. for (var item of items) {
  4. array = insertItemInArray(item, array, 2)
  5. }
  6. // Result = ["Sal", "Ben", "Lillie", "Maddie", "Lizzie", "David", "Chris"]

Listing 21-51 and Listing 21-52 show how to call the handlers in Listing 21-45 and Listing 21-46 to insert a list into a list at a specific position.

APPLESCRIPT

Open in Script Editor

Listing 21-51AppleScript: Calling a handler to insert a list at a specific position in a list
  1. set theList to {"Sal", "Ben", "David", "Chris"}
  2. insertItemInList({{"Lizzie", "Maddie", "Lillie"}}, theList, 3)
  3. --> Result: {"Sal", "Ben", {"Lizzie", "Maddie", "Lillie"}, "David", "Chris"}

JAVASCRIPT

Open in Script Editor

Listing 21-52JavaScript: Calling a function to insert a list at a specific position in an array
  1. var array = ["Sal", "Ben", "David", "Chris"]
  2. array = insertItemInArray(["Lizzie", "Maddie", "Lillie"], array, 2)
  3. // Result = ["Sal", "Ben", ["Lizzie", "Maddie", "Lillie"], "David", "Chris"]

Listing 21-53 and Listing 21-54 show how to call the handlers in Listing 21-45 and Listing 21-46 to insert a single item at the end of a list.

APPLESCRIPT

Open in Script Editor

Listing 21-53AppleScript: Calling a handler to insert a single item at the end of a list
  1. set theList to {"Sal", "Ben", "David", "Chris"}
  2. insertItemInList("Jen", theList, -1)
  3. --> {"Sal", "Ben", "David", "Chris", "Jen"}

JAVASCRIPT

Open in Script Editor

Listing 21-54JavaScript: Calling a function to insert a single item at the end of an array
  1. var array = ["Sal", "Ben", "David", "Chris"]
  2. array = insertItemInArray("Jen", array, array.length)
  3. // Result = ["Sal", "Ben", "David", "Chris", "Jen"]

Listing 21-55 and Listing 21-56 show how to call the handlers in Listing 21-45 and Listing 21-46 to insert a single item at the second-to-last position in a list.

APPLESCRIPT

Open in Script Editor

Listing 21-55AppleScript: Calling a handler to insert a single item at the second-to-last position in a list
  1. set theList to {"Sal", "Ben", "David", "Chris"}
  2. insertItemInList("Wanda", theList, -2)
  3. --> {"Sal", "Sue", "Bob", "Wanda", "Carl"}

JAVASCRIPT

Open in Script Editor

Listing 21-56JavaScript: Calling a function to insert a single item at the second-to-last position of an array
  1. var array = ["Sal", "Ben", "David", "Chris"]
  2. array = insertItemInArray("Jen", array, -1)
  3. // Result = ["Sal", "Ben", "David", "Jen", "Chris"]

Listing 21-57 and Listing 21-58 show how to call the handlers in Listing 21-45 and Listing 21-46 to insert a single item at a nonexistent position in a list.

APPLESCRIPT

Open in Script Editor

Listing 21-57AppleScript: Calling a handler to insert a single item at a position that doesn’t exist in a list
  1. set theList to {"Sal", "Ben", "David", "Chris"}
  2. insertItemInList("Jen", theList, 15)
  3. --> Result: false

JAVASCRIPT

Open in Script Editor

Listing 21-58JavaScript: Calling a function to insert a single item at a position that doesn’t exist in an array
  1. var array = ["Sal", "Ben", "David", "Chris"]
  2. array = insertItemInArray("Jen", array, 14)
  3. // Result = false

Replacing Items in a List

You can replace an item in a list using the syntax shown in Listing 21-59 and Listing 21-60 if you know the position of the item you want to replace.

APPLESCRIPT

Open in Script Editor

Listing 21-59AppleScript: Replacing a specific item in a list based on position
  1. set theList to {"Sal", "Ben", "David", "Chris"}
  2. set item 3 of theList to "Wanda"
  3. return theList
  4. --> Result: {"Sal", "Sue", "Wanda", "Carl"}

JAVASCRIPT

Open in Script Editor

Listing 21-60JavaScript: Replacing a specific item in an array based on position
  1. var array = ["Sal", "Ben", "David", "Chris"]
  2. array[2] = "Wanda"
  3. array
  4. // Result: ["Sal", "Ben", "Wanda", "Chris"]

The handlers in Listing 21-61 and Listing 21-62 can be used to replace an item in a list when you don’t know its position. Provide the item you want to replace, the list, the replacement item, and specify whether to replace all instances of the item, or just the first one.

APPLESCRIPT

Open in Script Editor

Listing 21-61AppleScript: Handler that replaces items in a list
  1. on replaceItemInList(theItem, theList, theReplacementItem, replaceAll)
  2. repeat with a from 1 to the count of theList
  3. set theCurrentItem to item a of theList
  4. if theCurrentItem is theItem then
  5. set item a of theList to theReplacementItem
  6. if replaceAll is false then return theList
  7. end if
  8. end repeat
  9. return theList
  10. end replaceItemInList

JAVASCRIPT

Open in Script Editor

Listing 21-62JavaScript: Function that replaces items in an array
  1. function replaceItemInArray(item, array, replacementItem, replaceAll) {
  2. var arrayLength = array.length
  3. for (var i = 0; i < arrayLength; i++) {
  4. var currentArrayItem = array[i]
  5. if (currentArrayItem === item) {
  6. array.splice(i, 1, replacementItem)
  7. if (!replaceAll) {
  8. break
  9. }
  10. }
  11. }
  12. return array
  13. }

Listing 21-63 and Listing 21-64 show how to call the handlers in Listing 21-61 and Listing 21-62.

APPLESCRIPT

Open in Script Editor

Listing 21-63AppleScript: Calling a handler to replace items in a list
  1. set theList to {"Sal", "Jen", "Ben", "David", "Chris", "Jen"}
  2. replaceItemInList("Jen", theList, "Lizzie", true)
  3. --> {"Sal", "Lizzie", "Ben", "David", "Chris", "Lizzie"}

JAVASCRIPT

Open in Script Editor

Listing 21-64JavaScript: Calling a function to replace items in an array
  1. var array = ["Sal", "Jen", "Ben", "David", "Chris", "Jen"]
  2. replaceItemInArray("Jen", array, "Lizzie", true)
  3. // Result: ["Sal", "Lizzie", "Ben", "David", "Chris", "Lizzie"]

Sorting a List

The handler in Listing 21-65 sorts a list of strings or numbers in AppleScript.

APPLESCRIPT

Open in Script Editor

Listing 21-65AppleScript: Handler that sorts a list of strings
  1. on sortList(theList)
  2. set theIndexList to {}
  3. set theSortedList to {}
  4. repeat (length of theList) times
  5. set theLowItem to ""
  6. repeat with a from 1 to (length of theList)
  7. if a is not in theIndexList then
  8. set theCurrentItem to item a of theList as text
  9. if theLowItem is "" then
  10. set theLowItem to theCurrentItem
  11. set theLowItemIndex to a
  12. else if theCurrentItem comes before theLowItem then
  13. set theLowItem to theCurrentItem
  14. set theLowItemIndex to a
  15. end if
  16. end if
  17. end repeat
  18. set end of theSortedList to theLowItem
  19. set end of theIndexList to theLowItemIndex
  20. end repeat
  21. return theSortedList
  22. end sortList

Listing 21-66 shows how to call the handler in Listing 21-65.

APPLESCRIPT

Open in Script Editor

Listing 21-66AppleScript: Calling a handler to sort a list of strings
  1. set theList to {"Sal", "Ben", "David", "Chris"}
  2. sortList(theList)
  3. --> Result: {"Ben", "Chris", "David", "Sal"}

To perform a reverse (descending) sort, use the reverse command, as shown in Listing 21-67.

APPLESCRIPT

Open in Script Editor

Listing 21-67AppleScript: Calling a handler to sort a list of strings in reverse order
  1. set theList to {"Sal", "Ben", "David", "Chris"}
  2. reverse of sortList(theList)
  3. --> Result: {"Sal", "David", "Chris", "Ben"}

In JavaScript, the Array object has a sort method, which sorts the array’s items. See Listing 21-68.

JAVASCRIPT

Open in Script Editor

Listing 21-68JavaScript: Sorting an array of strings
  1. var array = ["Sal", "Ben", "David", "Chris"]
  2. array.sort()
  3. // Result: ["Ben", "Chris", "David", "Sal"]

As in AppleScript, a sorted JavaScript array can be reversed, as shown in Listing 21-69.

JAVASCRIPT

Open in Script Editor

Listing 21-69JavaScript: Sorting an array of strings in reverse order
  1. var array = ["Sal", "Ben", "David", "Chris"]
  2. array.sort()
  3. array.reverse()
  4. // Result: ["Sal", "David", "Chris", "Ben"]