How to compare current value with previous value?

Robert Campbell
Tera Guru

I expected this small piece of code to show the value from this iteration and the previous

var ce = new GlideAggregate('cert_element');
count = 0;
ce.addAggregate('COUNT', 'configuration_item');
//ce.addQuery('sys_created_on', '>=', '2022-12-05');
ce.orderBy('configuration_item');
ce.orderBy('state');
ce.groupBy('configuration_item');
ce.query();

pre = '';// Set prevous value to nothing.

while(ce.next()){
  gs.print('Before -- Now: ' +ce.configuration_item.name+ '\tThen: ' +pre.configuration_item.name); // Properly shows the first value for Now and undefined for Then but only for the first time.  Every time after it shows the same value.
  pre = ce; // Set pre to cs and on the start of the next iteration, pre should be what cs is now and cs should change to the new value.
  gs.print('After  -- Now: ' +ce.configuration_item.name+ '\tThen: ' +pre.configuration_item.name); // Properly shows the same value because the new value was set to the old.
  count++;
}

gs.print(count);

The first time through, it shows ce as the new value and pre as nothing (undefined), which is right for "Before".

It then updates pre to ce and they show the same thing, which is right for "After".

The second time through, it shows ce as the new value of ce for ce and that same new value for pre.  I expected the value of pre to still be set to the previous value of ce until after it prints the "Before".

 

 

1 ACCEPTED SOLUTION

Elijah Aromola
Mega Sage

I believe this has to do with "pre" pointing at the same GlideRecord object each time. Do you need access to the entire GlideRecord object? Can you do something like the below code?

var ce = new GlideAggregate('cert_element');
count = 0;
ce.addAggregate('COUNT', 'configuration_item');
//ce.addQuery('sys_created_on', '>=', '2022-12-05');
ce.orderBy('configuration_item');
ce.orderBy('state');
ce.groupBy('configuration_item');
ce.query();

pre = {name: ""};

while(ce.next()){
  gs.print('Before -- Now: ' +ce.configuration_item.name+ '\tThen: ' +pre.name); // Properly shows the first value for Now and undefined for Then but only for the first time.  Every time after it shows the same value.
  pre.name = ce.configuration_item.name.toString() // Set pre to cs and on the start of the next iteration, pre should be what cs is now and cs should change to the new value.
  gs.print('After  -- Now: ' +ce.configuration_item.name+ '\tThen: ' +pre.name); // Properly shows the same value because the new value was set to the old.
  count++;
}

gs.print(count);

 

View solution in original post

5 REPLIES 5

I have expanded or maybe rewrote it but I'm not able to return the record because I'm not comparing a record to another, I'm only comparing part of a record to part of another and then I want the "winner" record.  How to get the correct record (sys_id) from a script when comparing arrays?