Sorting a Multi Row Variable Set

Brad Bowman
Kilo Patron
Kilo Patron

I have a multi row variable set with three single line text variables: v_string1, v_string2, and v_string3.  The MRVS will be populated on the request form.  In the workflow, I would like a Run Script to sort the contents alphabetically, ascending, by v_string2, so that when the MRVS is shown on the RITM and any tasks (where it will be read-only), it will appear in this new sorted order, rather than the order in which the requestor added the rows.  I'm having trouble coming up with the right syntax/logic to do this. 

1 ACCEPTED SOLUTION

Ankur Bawiskar
Tera Patron
Tera Patron

@Brad Bowman 

you can try something like this in the workflow run script

It worked well for me. It sorted the MRVS based on key I gave

Reference: https://stackoverflow.com/questions/8175093/simple-function-to-sort-an-array-of-objects

var jsonString = current.variables.<mrvs_variableName>;

var key = 'v_string2';

var array = JSON.parse(jsonString);

var finalObj = sort_by_key(array, key);

current.variables.<mrvs_variableName> = JSON.stringify(finalObj);

current.setWorkflow(false);

current.update();

function sort_by_key(array, key)
{
 return array.sort(function(a, b)
 {
  var x = a[key]; var y = b[key];
  return ((x < y) ? -1 : ((x > y) ? 1 : 0));
 });
}

Regards
Ankur

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

View solution in original post

4 REPLIES 4

Ct111
Giga Sage

Ankur Bawiskar
Tera Patron
Tera Patron

@Brad Bowman 

you can try something like this in the workflow run script

It worked well for me. It sorted the MRVS based on key I gave

Reference: https://stackoverflow.com/questions/8175093/simple-function-to-sort-an-array-of-objects

var jsonString = current.variables.<mrvs_variableName>;

var key = 'v_string2';

var array = JSON.parse(jsonString);

var finalObj = sort_by_key(array, key);

current.variables.<mrvs_variableName> = JSON.stringify(finalObj);

current.setWorkflow(false);

current.update();

function sort_by_key(array, key)
{
 return array.sort(function(a, b)
 {
  var x = a[key]; var y = b[key];
  return ((x < y) ? -1 : ((x > y) ? 1 : 0));
 });
}

Regards
Ankur

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

Worked like a charm.  Thanks!  I was heading down that road but it didn't work due to not parsing first - I never seem to know when that's needed and when it's not with MRVS scripting.

You are welcome.

Regards
Ankur

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader