A function to sort the items in an array and remove duplicates.
Can probably be used for an array containing any object types. Script below shows it working for strings.
Useful for removing duplicates from an array containing a list of element names (or anything else).
For example, perhaps you use getElementsByTagName() or getNodesByXPath() and then use the nodeName property and a loop to assign all the element names returned by those APIs to items in an array. If you think this array is likely to contain duplicate names you could use this function to remove the duplicates before populating a listbox, combobox, or other type of control in an XFT form, or before populating a message for a report, or elsewhere.
The following demonstrates a simple call to this function that passes a hard coded array followed by what I consider to probably be a more likely use case that works on nodeNames.
//XMetaL Script Language JScript:
function unique(arr){
arr.sort();
for(var i = 1;i < arr.length;){
if(arr[i-1] == arr[i]){
arr.splice(i, 1);
}
else{
i++;
}
}
}
//Demo: hard-coded array
var myArray = new Array("b","a","b","b","c","c","a","c","c","b");
var msg = "Hard-Coded String Array\n\n";
msg += "Before:\t" + myArray;
unique(myArray);
msg += "\nAfter:\t" + myArray;
Application.Alert(msg);
//Demo: elements in current document
var allNodes = ActiveDocument.getElementsByTagName("*");
var allNames = new Array();
for (i=0;i<allNodes.length;i++) {
allNames[i] = allNodes.item(i).nodeName;
}
var msg = "Elements in Document\n\n";
msg += "Directly from DOM:\n" + allNames;
unique(allNames);
msg += "\n\nList of Element Names Used:\n" + allNames;
Application.Alert(msg);