Make array unique

Sunny14
Tera Contributor

Hello Team,

 

I have below code which brings records which has duplicate Users.  [licenseRec.user] 

How can I make this into store only unique User records?

Currently both of my array length is coming out same. [i.e. icenseRec  & arrayUnq ] 

 

 

var licenseRec = new GlideRecord('sys_user_has_role');
licenseRec.addEncodedQuery("XXX");
licenseRec.query();
gs.info(licenseRec.getRowCount());

var arrayUnq = [];
while (licenseRec.next()){
    arrayUnq.push(licenseRec.user);
}
gs.info(arrayUnq.length);
 
1 ACCEPTED SOLUTION

@Sunny14 

try this

var licenseRec = new GlideRecord('sys_user_has_role');
licenseRec.addEncodedQuery("xxx");
licenseRec.query();
gs.info(licenseRec.getRowCount());

var arrayUnq = [];
while (licenseRec.next()) {
    arrayUnq.push(licenseRec.user.toString());
}
arrayUnq = new global.ArrayUtil().unique(arrayUnq);
gs.info(arrayUnq.length);
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

View solution in original post

8 REPLIES 8

Hi @Sunny14 ,

 

As I can see the output of script is different it shows record count on query is 9811, and when applied unique arrayUtil is printing 1, means it is working. It might be the issue with your query

 

I have tried with below it is working. see below

var arr=["bh","md","kj","bh","ew","md","kj","we","we"];
arr=new global.ArrayUtil().unique(arr)
gs.info("Array Length: "+arr.length+", New Array: "+arr)

 

and the Output is 

 

*** Script: Array Length: 5, New Array: bh,ew,md,kj,we

 

Thanks,
Bhimashankar H

 

-------------------------------------------------------------------------------------------------
If my response points you in the right directions, please consider marking it as 'Helpful' & 'Correct'. Thanks!

Hello @Bhimashankar H 

Thank you for your response. Yes, this is working fine as well. 

@Sunny14 

 

Script I provided was to remove duplicate elements from Array. Check your while loop as I believe there is a mismatch in data type.

 

Below is the sample for unique array,

 

Bhuvan_0-1754635074445.png

Bhuvan_1-1754635100890.png

Thanks,

Bhuvan

 

 

Thanks @Bhuvan  

I think the magic was to add .toString() 

 

Thanks a lot.