XMetaL Tips and Tricks
XMetaL Community Forum › XMetaL Tips and Tricks › Script Example: Remove duplicates from a JScript Array
-
Derek Read March 3, 2010 at 1:43 am
Script Example: Remove duplicates from a JScript Array
March 3, 2010 at 1:43 amParticipants 1Replies 0Last Activity 13 years, 1 month agoA 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.
[code]//XMetaL Script Language JScript:
function unique(arr){
arr.sort();
for(var i = 1;i < arr.length;){
if(arr[i-1] == arr){
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 Arraynn”;
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;iallNames = allNodes.item(i).nodeName;
}
var msg = “Elements in Documentnn”;
msg += “Directly from DOM:n” + allNames;
unique(allNames);
msg += “nnList of Element Names Used:n” + allNames;
Application.Alert(msg);[/code] -
AuthorPosts
- You must be logged in to reply to this topic.