Compare more than 1 records and get the latest record.

madanm7786
Mega Guru

Hi All,

Need help....

I have a custom table with below records.

ITEMNameUpdated
SNOWSN12312/6/2024
SNOWSN45615/8/2024

I need to compare these 2 records based on updated field.

After comparing i need to perform 2 actions.

For recently Updated: get the name field value(SN456) and add it to another table.

For earlier updated: get the name field value(SN123) and delete the record from another table.

Need help in comparing and getting the Name field value. I am able compare the updated field, but stuck in how to get associated Name field value.

Below is the script i written

var cnt =[];
var latest;
var old;
var gr = new GlideRecord('u_item');
gr.addEncodedQuery('u_item=snow');
gr.query();
while(gr.next())
{
cnt.push(gr.u_updated.toString();
}

if(cnt.length > 1)
{
latest = cnt[0];
for(var i=0;i<cnt.length;i++)
{
if(cnt[i] > latest)
{
latest = cnt[i];

here i need the recently updated Name field value.(SNOW 456)
}
else
{
old = cnt[i];

here i need the earlier updated Name field value.(SNOW 123)
}
}
}

 

 

1 ACCEPTED SOLUTION

anshul_goyal
Kilo Sage

Hi @madanm7786,

Please try the below code and see if it works for you:

 

var cnt = [];
var latest, old, name;
var gr = new GlideRecord('u_item');
gr.addEncodedQuery('u_item=snow');
gr.query();
while (gr.next()) {
    cnt.push({
        "updatedDate": gr.u_updated.toString(),
        "name": gr.u_name.toString()
    });
}

if (cnt.length > 1) {
    latest = cnt[0].updatedDate;
    for (var i = 0; i < cnt.length; i++) {
        if (cnt[i].updatedDate > latest) {
            latest = cnt[i].updatedDate;
            name = cnt[i].name;
        } else {
            old = cnt[i].updatedDate;
            name = cnt[i].name;
        }
    }
}

 


Please mark my solution as Helpful and Accepted, if it works for you in any way!

Thanks

View solution in original post

2 REPLIES 2

anshul_goyal
Kilo Sage

Hi @madanm7786,

Please try the below code and see if it works for you:

 

var cnt = [];
var latest, old, name;
var gr = new GlideRecord('u_item');
gr.addEncodedQuery('u_item=snow');
gr.query();
while (gr.next()) {
    cnt.push({
        "updatedDate": gr.u_updated.toString(),
        "name": gr.u_name.toString()
    });
}

if (cnt.length > 1) {
    latest = cnt[0].updatedDate;
    for (var i = 0; i < cnt.length; i++) {
        if (cnt[i].updatedDate > latest) {
            latest = cnt[i].updatedDate;
            name = cnt[i].name;
        } else {
            old = cnt[i].updatedDate;
            name = cnt[i].name;
        }
    }
}

 


Please mark my solution as Helpful and Accepted, if it works for you in any way!

Thanks

Hi Anshul,

It worked. Thanks.....