Remove duplicates from the string variable type.

soundarya_123
Tera Contributor

There is a use case table with a field called 'mandate variables,' where backend variable names are added. This use case table is associated with the current catalog item. I have written a script to retrieve the variable names from the 'mandate variables' field in the use case, but it is not removing the duplicate entries from the array.

 

var va = '6e263fa6875e121046e3ca6e8bbb358a';

var arr = [];

var gr = new GlideRecord('u_sc_catalog_item_use_case');

gr.addQuery('u_catalog_item', va); //itemObj

gr.query();

 

 

var allMandateVariables = [];

var uniqueMandateVariables = [];

 

while (gr.next()) {

    var mandateVariables = gr.getValue('u_mandate_variables');

    if (mandateVariables) { // Check if mandateVariables is not empty

        allMandateVariables.push(mandateVariables);

   

    }

}

 

uniqueMandateVariables = new ArrayUtil().unique(allMandateVariables);

gs.print(uniqueMandateVariables);

9 REPLIES 9

Ankur Bawiskar
Tera Patron
Tera Patron

@soundarya_123 

are you in custom scope?

if yes then you should use this syntax global.ArrayUtil

If not then what came in logs? did you add that?

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

The scope is Global, I tried in the background script but the output contains all the variable names without cutting off the duplicates. The result is attached.

soundarya_123_0-1744287397038.png

 

@soundarya_123 

try this

ArrayUtil requires array and not string

var va = '6e263fa6875e121046e3ca6e8bbb358a';

var gr = new GlideRecord('u_sc_catalog_item_use_case');
gr.addQuery('u_catalog_item', va); //itemObj
gr.query();

var allMandateVariables = [];

while (gr.next()) {
    var mandateVariables = gr.getValue('u_mandate_variables');
    if (mandateVariables) { // Check if mandateVariables is not empty
        var variablesArray = mandateVariables.split(','); // Split the string into an array
        allMandateVariables = allMandateVariables.concat(variablesArray); // Add to the main array
    }
}

var uniqueMandateVariables = new ArrayUtil().unique(allMandateVariables);
gs.print(uniqueMandateVariables);

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

Robert H
Mega Sage

Hello @soundarya_123 ,

 

Please replace this line:

allMandateVariables.push(mandateVariables);

with this:

allMandateVariables = allMandateVariables.concat(mandateVariables.split(',')); 

 

Reason: "mandateVariables" is a comma separated string of variable names, so you first need to split them into individual array elements before looking for duplicates.

 

Regards,

Robert