JavaScript Grouped Order By
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
10-17-2022 03:58 AM
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.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
10-17-2022 06:56 AM
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.

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
10-19-2022 10:03 AM
@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.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
10-21-2022 06:22 AM
@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.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
10-21-2022 07:21 AM
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.