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 04:26 AM
Hi Daniel,
Please see if this can help.
How to get the Top 10 values from a table using the GlideAggregate function
Mark Correct and Helpful if it helps.
***Mark Correct or Helpful if it helps.***
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
10-17-2022 04:33 AM
try this
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();
},
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
10-17-2022 06:58 AM
Thank you for your reply, I've tried removing that line and still no luck.

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
10-17-2022 04:34 AM - edited 10-17-2022 04:40 AM
I think you can just use gr.orderByAggregate('COUNT'); to achieve it.
getDuplicateAssetforAssignedTo: function() {
var str = [];
var gr = new GlideAggregate('cmdb_ci');
gr.addAggregate('COUNT', 'serial_Number');
gr.groupBy('serial_Number');
gr.addHaving('COUNT', '>', 1);
gr.orderByAggregate('COUNT');
gr.query();
while (gr.next()) {
str.push(gr.getValue('serial_Number') + '');
}
return str.toString();
},
});
Reference
Please mark this response as correct or helpful if it assisted you with your question.