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 this is useful 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
The JavaScript / ECMAScript code is show below.
function RemoveArrayItems(itemsToRemove,array)
{
if (array.length == 0 || itemsToRemove.length==0) return array;
var sMatchedItems = "|" + itemsToRemove.join('|') + "|";
var newArray=[];
for (var i = 0;i < array.length;i++)
{
if (sMatchedItems.indexOf("|" + array[i] + "|") < 0)
{
newArray[newArray.length] = array[i];
}
}
if (newArray.length > 0)
{
form.setValues("fldGroupChange", "TRUE");
}
return newArray;
}
Given the function listed above, it can be used as shown in the example below.
var newArray = form.getValues("fldGroup");
var oldArray = form.getValues("fldOldGroup");
var newItemsAdded = RemoveArrayItems(oldArray,newArray);
var ItemsRemoved = RemoveArrayItems(newArray,oldArray);
form.setValues("fldAddedGroup", newItemsAdded);
form.setValues("fldDeletedGroup", ItemsRemoved);
- The fldGroup field is where the current Groups assigned to a User are populated.
- 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.