XMetaL Home Page XMetaL Community Forum
Welcome, Guest. Please login or register.
Did you miss your activation email?
September 10, 2010, 08:00:30 PM
2836 Posts in 834 Topics by 1937 Members
Latest Member: Nick V
XMetaL Community Forums  |  General  |  XMetaL Tips and Tricks  |  Script Example: Remove duplicates from a JScript Array « previous next »
Pages: 1
Author Topic: Script Example: Remove duplicates from a JScript Array  (Read 779 times)
Derek Read
Program Manager (XMetaL)
Administrator
Member

Posts: 847



WWW
« on: March 02, 2010, 07:43:54 PM »

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.

Code:
//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);
Logged

Derek Read, Program Manager (XMetaL)
Pages: 1
XMetaL Community Forums  |  General  |  XMetaL Tips and Tricks  |  Script Example: Remove duplicates from a JScript Array « previous next »
Jump to: