Array values are not getting printed correctly

Kiruthikroshan
Tera Contributor

Hi,

 

I need a help regarding a Background script.

 

I need to fetch and print first 5 users from each Department the User table. Below is the script that I have written.

 

var dep = new GlideAggregate('sys_user');
dep.addNotNullQuery('department');
dep.groupBy('department');
dep.query();
while(dep.next())
{
    var dept = dep.department;
    gs.print("Department is " + dept.getDisplayValue());
        var array = [];
        var user = new GlideRecord('sys_user');
        user.addQuery('department',dept);
        user.orderBy('name');
        gr.setLimit( 5 );
        user.query();
        while(user.next())
        {
            array.push(user.name);
        }
        gs.print(array);    
}
 
After running the script, it gives output as attached. Please help me to find what is wrong with my script.
Thanks,
Kiruthikroshan M
1 ACCEPTED SOLUTION

Mohammed8
Giga Sage

Hi @Kiruthikroshan  ,

I Ran your script and getting the following error, you can check:

Mohammed8_2-1763480239132.png

 

I made changes to your script

 

var dep = new GlideAggregate('sys_user');

dep.addNotNullQuery('department');

dep.groupBy('department');

dep.query();

while (dep.next()) {

    var dept = dep.department;  // sys_id

    gs.print("Department is " + dept.getDisplayValue());

    var array = [];

    var user = new GlideRecord('sys_user');

    user.addQuery('department', dept);

    user.orderBy('name');

    user.setLimit( 5 );    // FIXED

    user.query();

    while (user.next()) {

        array.push(user.name.getDisplayValue());  

    }

    gs.print(array.join(", "));

}

 

Getting result as per your usecase:

 

Mohammed8_1-1763480112991.png

 

If you find this useful, mark as helpful/solution accepted.

 

Regards,

Mohammed Zakir

View solution in original post

1 REPLY 1

Mohammed8
Giga Sage

Hi @Kiruthikroshan  ,

I Ran your script and getting the following error, you can check:

Mohammed8_2-1763480239132.png

 

I made changes to your script

 

var dep = new GlideAggregate('sys_user');

dep.addNotNullQuery('department');

dep.groupBy('department');

dep.query();

while (dep.next()) {

    var dept = dep.department;  // sys_id

    gs.print("Department is " + dept.getDisplayValue());

    var array = [];

    var user = new GlideRecord('sys_user');

    user.addQuery('department', dept);

    user.orderBy('name');

    user.setLimit( 5 );    // FIXED

    user.query();

    while (user.next()) {

        array.push(user.name.getDisplayValue());  

    }

    gs.print(array.join(", "));

}

 

Getting result as per your usecase:

 

Mohammed8_1-1763480112991.png

 

If you find this useful, mark as helpful/solution accepted.

 

Regards,

Mohammed Zakir