Built something you're proud of? Tell the story. A quick G2 review of App Engine or Build Agent helps other developers see what's possible on ServiceNow. Share your experience.

How to remove the duplicate values via script

Roshini
Tera Guru

Hi Team,
Am trying to print the parent incident number + count of child incidents to the respective parent incident. Below is my code, but if there is two child incidents in my list am getting the print two times, how to remove the duplicate entry.

Code

var a = new GlideRecord('incident');
a.addEncodedQuery('parent_incident!=NULL');
a.query();
while (a.next())
{
var b = new GlideAggregate('incident');
b.addQuery('parent_incident',a.parent_incident);
b.addAggregate('COUNT');
b.query();
if(b.next())
{
    gs.print(" Incident " + a.parent_incident.number + " count is "+ b.getAggregate('COUNT'));
}

 

}
2 REPLIES 2

Brad Bowman
Mega Patron

You can simply add a check to not run the aggregate twice for the same parent incident:

 

var parInc = '';
var a = new GlideRecord('incident');
a.addEncodedQuery('parent_incident!=NULL');
a.query();
while (a.next()) {
	if (parInc != a.parent_incident) {
		parInc = a.parent_incident.toString();
    	var b = new GlideAggregate('incident');
    	b.addQuery('parent_incident', a.parent_incident);
    	b.addAggregate('COUNT');
    	b.query();
    	if (b.next()) {
        	gs.print(" Incident " + a.parent_incident.number + " count is " + b.getAggregate('COUNT'));
    	}
	}
}

 

 

SAI VENKATESH
Kilo Patron

Hi @Roshini 

 

You can try the below Script:

var agg = new GlideAggregate('incident');
agg.addEncodedQuery('parent_incident!=NULL');
agg.groupBy('parent_incident');         
agg.addAggregate('COUNT');               
agg.query();

var existingincidents = [];

while (agg.next()) {
    var parentIncidentnumber = agg.parent_incident.number; 
    
    if (existingincidents.indexOf(parentIncidentnumber) === -1) {
        var childCount = agg.getAggregate('COUNT'); 
        gs.print("Incident " + parentIncidentnumber + " count is " + childCount);
        existingincidents.push(parentIncidentnumber);
    }
}

 

Thanks and Regards

Sai Venkatesh