ECMAScript to compare two arrays

It is sometimes useful to be able to compare two arrays before loading the result into an MVEditor or a list. A few scenarios of when you might want to use this code are:

  • When you want to determine which Groups to display to a User on a Workflow form, knowing that some Groups are restricted and should not be displayed
  • When you want to know the value(s) which the User has modified in a list of items. An item may have been added or removed by the User
  • When you want to display text to the User, keeping track of additions and deletions to and from a list
Given the function listed above, it can be used as shown in the example below.
  1. The fldGroup field is where the current Groups assigned to a User are populated.
  2. The fldOldGroup field is a copy of the Groups, and is populated so I can keep track of the added and removed Groups.

When the logged in User modifies the Groups assigned to a User, I compare oldArray and newArray (to get the added) and also newArray and oldArray (to get the Deleted). This makes it very easy to run a loop around the added Array and the deleted Array and only manipulate that data on the User. This is better coding, in my opinion, than always replacing the values regardless of whether they have changed or not.