XMetaL Tips and Tricks

XMetaL Community Forum XMetaL Tips and Tricks Script Example: Remove duplicates from a JScript Array

  • Derek Read

    Script Example: Remove duplicates from a JScript Array

    Participants 1
    Replies 0
    Last Activity 12 years, 4 months ago

    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){
    for(var i = 1;i < arr.length;){
    if(arr[i-1] == arr){
    arr.splice(i, 1);

    //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;
    msg +=  “nAfter:t” + myArray;

    //Demo: elements in current document
    var allNodes = ActiveDocument.getElementsByTagName(“*”);
    var allNames = new Array();
    for (i=0;i allNames
    = allNodes.item(i).nodeName;
    var msg = “Elements in Documentnn”;
    msg += “Directly from DOM:n” + allNames;
    msg +=  “nnList of Element Names Used:n” + allNames;


  • You must be logged in to reply to this topic.

Lost Your Password?