Sort Mendix Objects in a nanoflow [answered]

11
Hi, I thought this maybe useful for someone in future who wish to sort objects in a nanoflow and use Mendix versions with JS Actions available. Use this js code in a js action:   // This file was generated by Mendix Studio Pro. // // WARNING: Only the following code will be retained when actions are regenerated: // - the import list // - the code between BEGIN USER CODE and END USER CODE // - the code between BEGIN EXTRA CODE and END EXTRA CODE // Other code you write will be lost the next time you deploy the project. import { Big } from "big.js"; // BEGIN EXTRA CODE // END EXTRA CODE /** * Sorts a list of Mendix Objects by Attribute Name and Sort Order specified. See Param documentation for more information. * @param {string} sortByAttributeName - Required. Specify the Attribute name you wish to sort the objects on. It must a valid full attribute name existing the entity of the Objects paramater. * @param {"Asc"|"Desc"} sortOrder - Enumeration of Asc and Desc. You may have to manually create this Enum in your project. * @param {MxObject[]} objects - Required List of AnyObjects to be sorted by AttributeName * @returns {Promise.<MxObject[]>} */ export async function JS_SortMendixObjectsByKey(sortByAttributeName, sortOrder, objects) { // BEGIN USER CODE if (!sortByAttributeName) { throw new TypeError("Input parameter 'SortByAttributeName' is required"); } if (!objects) { throw new TypeError("Input parameter 'Objects' is required"); } var sortedObjects = objects.sort(compareValues(sortByAttributeName,sortOrder.toLowerCase())); return sortedObjects; function serializeMxObject(object) { return object.getAttributes().reduce(function (accumulator, attributeName) { accumulator[attributeName] = object.get(attributeName); return accumulator; }, { guid: object.getGuid() }); } function compareValues(key, order = 'asc') { return function innerSort(objA, objB) { const a = serializeMxObject(objA); const b = serializeMxObject(objB); if (!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) { // property doesn't exist on either object return 0; } const varA = (typeof a[key] === 'string') ? a[key].toUpperCase() : a[key]; const varB = (typeof b[key] === 'string') ? b[key].toUpperCase() : b[key]; let comparison = 0; if (varA > varB) { comparison = 1; } else if (varA < varB) { comparison = -1; } return ( (order === 'desc') ? (comparison * -1) : comparison ); }; } // END USER CODE }    
asked
1 answers
1

As this was more a knowledge post and the user answered their own question I added this text to mark the post as answered.

answered