The CreatorCon Call for Content is officially open! Get started here.

How to sort Key value pair array

sainath3
Mega Guru

Hi Team,

 

Table 1:

 

NameID
Bachu Sainath101

 

Table 2:

 

IDAmountBranch
10120Delhi
10180Pune
10130Bangalore
10110Hyd

 

Requirement is to Print Branch with Amount in Descending order (Amount):

Expected Output in Table 1:

NameIDBranch1Amount1Branch2Amount2Branch3Amount3Branch4Amount4
Bachu Sainath101Pune80Bangalore30Delhi20Hyd10

 

My code:

var branch,amount;

var amountForbranch={ };

var gr=new GlideRecord('table1');

gr.addQuery('ID','101');

gr.query();

if(gr.next()){

var gr1=new GlideRecord('table2');

gr1.addQuery('ID',gr.id);

gr1.query();

while(gr1.next()){

branch=gr1.branch.toString();

amount=gr1.amount.toString();

amountForbranch[branch]=amount;

}

for(var key in amountForbranch){
gs.info(" key is " + key + " amountForbranch[key] " + amountForbranch[key]);

}

}

Actual Output is:

key is Delhi amountForbranch[key] 20
key is Pune amountForbranch[key] 80
key is Bangalore amountForbranch[key] 30
key is Hyd amountForbranch[key] 10

 expected output is:

 key is Pune amountForbranch[key] 80
key is Bangalore amountForbranch[key] 30
key is Delhi amountForbranch[key] 20
key is Hyd amountForbranch[key] 10

Please help me how to sort Amount & Branch in Descending order.

5 REPLIES 5

Ben_G
Tera Expert

If the values are stored on the table already, an orderByDesc("amount") would do it.

Sorry, I forgot to mention one more step of requirement.

In Table 2

var lineamount = covert_currency(gr1.u_currency, 'EUR', gr1.amount);//Convert Amount to EUR

amount=lineamount.toString();

Need to sort the amount after the Conversion

Karan Chhabra6
Mega Sage

Hi @sainath3 ,

 

You can use the orderByDesc() method in your code to sort it by amount.

Please refer to the code below:

var branch,amount;

var amountForbranch={ };

var gr=new GlideRecord('table1');

gr.addQuery('ID','101');

gr.query();

if(gr.next()){

var gr1=new GlideRecord('table2');

gr1.addQuery('ID',gr.id);
gr1.orderByDesc('amount'); 

gr1.query();

while(gr1.next()){

branch=gr1.branch.toString();

amount=gr1.amount.toString();

amountForbranch[branch]=amount;

}

for(var key in amountForbranch){
gs.info(" key is " + key + " amountForbranch[key] " + amountForbranch[key]);

}

}

 

 

If my answer has helped with your question, please mark it as correct and helpful

 

Thanks!

Hi Karan,

 

Sorry, I forgot to mention one more step of requirement.

In Table 2

var lineamount = covert_currency(gr1.u_currency, 'EUR', gr1.amount);//Convert Amount to EUR

amount=lineamount.toString();

Need to sort the amount after the Conversion