Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

JavaScript Grouped Order By

Daniel Banks
Tera Contributor

Hi All,

 

I am new to ServiceNow and completely new to JavaScript. I have been trying to work on running a JavaScript query adapting what I have found elsewhere which works fine. However, I am wanting to now add a sort by or sort by descending order for the grouped count. 

 

I have seen on previous posts something along the lines of below:

 

var gr = new GlideRecord('alm_asset');
gr.orderBy('display_name'); // Ascending Order
//gr.addEncodedQuery(queryString);
gr.query();
while (gr.next()) {
gr.orderByDesc()
gs.info(gr.number+" P:"+gr.display_name);
}

 

 

However, I'm having trouble adapting this into my current script and get it to work: -

 

getDuplicateAssetforAssignedTo: function() {
var str = [];
var gr = new GlideAggregate('cmdb_ci');
gr.addAggregate('COUNT', 'serial_Number');
gr.groupBy('serial_Number');
gr.addHaving('COUNT', '>', 1);
gr.query();
while (gr.next()) {
str.push(gr.getValue('serial_Number') + '');
}
return str.toString();

},
});

 

Any help will be much appreciated and thank you in advance for your help on the above.

8 REPLIES 8

Thank you for your reply it is very much appreciated, unfortunately, this solution hasn't worked as still get the same results as before where the count numbers aren't arranged. 

DanielBanks_1-1666014938315.png

 

 

SanjivMeher
Mega Patron
Mega Patron

@Daniel Banks Could you please mark the answer correct, if it worked for you.


Please mark this response as correct or helpful if it assisted you with your question.

@SanjivMeher as mentioned in the reply above unfortunately this does not work when testing in the two environments, I have access to and at present is still unresolved.

thomaskennedy
Tera Guru

I think what you're trying to do is order the groups by the count of each aggregate. Try this.

 

var arr = [];
var gr = new GlideAggregate('cmdb_ci');
gr.addQuery('serial_number', '!=', '');
gr.addHaving('COUNT', '>', 1);
gr.addAggregate('COUNT', 'serial_number');
gr.orderByAggregate('COUNT', 'serial_number');
gr.query();
while (gr.next()) {
arr.push(gr.getValue('serial_number'));
}
gs.info( arr )

The orderByAggregate method seems to require two arguments. When I omit the second I get no output.

I suggest not naming your variable str if you're not capturing a string. Here I named it arr.

You can omit the trailing  +'' if you're using getValue. This method doesn't return a reference so there's no need to stringify it.