Sort/OrderBy values in Array.

Wesley Breshear
Tera Expert

Hello,

Hopefully, this is an easy one to solve.  Just need to sort my array based on the 'sysProperty.getDisplayValue('description');'.  I have looked at few KB articles and tried various methods but since my sorting needs to occur in or after the While loop, I am lost how to sort (orderBy) my array.  This is my 'Server Script' section of a Service Portal Widget.

(function () {
	data.appProperties = [];
	var sysCategory = new GlideRecord('sys_properties_category_m2m');
	sysCategory.addQuery('category','0c14fbf0db20ebc02911e525ca9619f9'); //REST API Business Services
	sysCategory.query();
	while (sysCategory.next()) {
		var appProperty = {};
			var sysProperty = new GlideRecord('sys_properties');
			sysProperty.addQuery('sys_id',sysCategory.property);
			sysProperty.query();
			while (sysProperty.next()) {
				appProperty.groupName = sysProperty.getDisplayValue('description');
				appProperty.propertyValue = sysProperty.getDisplayValue('name');
				//appProperty.orderBy(sysProperty.getDisplayValue('description'));  //Failure to sort
				//appProperty.orderBy('groupName');  //Failure to sort
			}
			//var sortList = sysProperty.orderby('appProperty.groupName');  //Failure to sort
  		    //data.appProperties.push(sortList);

		data.appProperties.push(appProperty);
		}
})();

 

Here is the current look/output.  Need to sort/orderby alphabetically on the Business Service Name column [sysProperty.getDisplayValue('description')].

find_real_file.png

Thank you for your assistance.

-Wesley

 

12 REPLIES 12

bbf3562
Kilo Guru

Have you tried to add like sysProperty.orderBy('description')before sysProperty.query();?

If doesn't work then maybe use .sort()?

Here is an example of how to use it,

https://www.geeksforgeeks.org/javascript-array-sort/

Wesley Breshear
Tera Expert

Hi bbf3562,

I did with no success either and your other example seems to work if the array has already been created or established.  I think in my case the Array is being built in the while loop. 

while (sysCategory.next()) {
		var appProperty = {};
			var sysProperty = new GlideRecord('sys_properties');
			sysProperty.addQuery('sys_id',sysCategory.property);
		    sysProperty.orderBy('description'); 
			sysProperty.query();
			while (sysProperty.next()) {
				appProperty.groupName = sysProperty.getDisplayValue('description');
				appProperty.propertyValue = sysProperty.getDisplayValue('name');			
			}			
		data.appProperties.push(appProperty);
		}

-Wesley

I have two suggestions:

1) there is an OOB Script Include ArrayUtil (although it does not sort)

2) try orderby in your query BEFORE adding to your array

On a similar note, move the "var appProperty = {};" inside the (inner) while loop. Best practice is to initialize the object in the scope it is going to be used.