Business object lists in BPM are TWList objects, not JavaScript arrays: tw.local.orders.sort(...) does not exist on 8.5.x (recent BAW releases expose toArray() on lists). The portable way: copy to an array, sort, copy back:
// server-side script: sort tw.local.orders (list of Order) by total, descending, then by number
var arr = [];
for (var i = 0; i < tw.local.orders.listLength; i++) arr.push(tw.local.orders[i]);
arr.sort(function (a, b) {
if (b.total !== a.total) return b.total - a.total; // numbers
return (a.number || "").localeCompare(b.number || ""); // strings
});
var sorted = new tw.object.listOf.Order();
for (var j = 0; j < arr.length; j++) sorted.insertIntoList(j, arr[j]);
tw.local.orders = sorted;
// generic helper: sortListBy(list, field, direction)
function sortListBy(list, field, desc) {
var arr = []; for (var i = 0; i < list.listLength; i++) arr.push(list[i]);
arr.sort(function (a, b) {
var x = a[field], y = b[field];
if (x instanceof Date || (x && x.getTime)) { x = x.getTime(); y = y.getTime(); } // dates
var r = (typeof x === "number" && typeof y === "number") ? x - y : String(x == null ? "" : x).localeCompare(String(y == null ? "" : y));
return desc ? -r : r;
});
return arr; // caller copies back into a typed list (see below)
}// simpler generic helper: sort in place by replacing the elements (keeps the list type)
function sortList(list, cmp) {
var arr = []; for (var i = 0; i < list.listLength; i++) arr.push(list[i]);
arr.sort(cmp);
for (var j = 0; j < arr.length; j++) list[j] = arr[j];
}
sortList(tw.local.orders, function (a, b) { return new Date(b.created) - new Date(a.created); }); // newest firstClient side (coach): the bound list of a UI Toolkit table is a plain array with items on some releases - use var d = ${Table}.getData(); d.sort(cmp); ${Table}.setData(d);, or simply make the columns sortable and let the user click. Stable sorting: JavaScript's sort is stable in modern engines and in Rhino on BAW; on old Rhino add the index as a tiebreaker.
References