Compare lists in AppleScript

Posted in AppleScript on May 07, 2017 · 1 min read
Is there a way in AppleScript you can compare two lists to find what is missing in the second list?

We compare two lists in AppleScript by first creating the initial list:

set list1 to {"apple", "orange", "apple", "watermelon", "pear", "strawberry"}

Then we create the list we want to compare it to:

set list2 to {"apple", "orange", "watermelon"}

We call a third list so we can push any of the items found in list1 but not in list2

set list3 to {}

With all of the lists created we need to loop through the first list using a repeat:

repeat with x from 1 to count of items of list1
end repeat

In the repeat a variable of the list1 item's needs to be created so we can compare:

repeat with x from 1 to count of items of list1
    set n to item x of list1
end repeat

We write our conditional to compare the two lists and if the string isn't in both we push to the empty list, list3:

repeat with x from 1 to count of items of list1
    set n to item x of list1
    if n is in list1 and n is not in list2 then set end of list3 to n
end repeat

which could also be written as:

repeat with x from 1 to count of items of list1
    set n to item x of list1
    if n is in list1 and n is not in list2 then
        set end of list3 to n
    end if
end repeat

If you want the return of the contents in list3 you would simply write a return:

return list3

In the result window of script editor you should see:

{"pear", "strawberry"}
Help the site go ad free:
Storm Trooper