The integrated sort function for array
Array.sort() will sort the array ascending. This works good for scalar types like number. But how to sort descending (not using Array.reverse()) or sorting arrays containing complex types like virtual machines? Let's have a look.
The example above will log this:
The following example is sorting descending:
The example will log this:
The function "desc" returns a boolean to decide to sort or not. It works as comparator for the sorting algorithm inside
sort(). I don't know this algorithm, but this is not necessary. Just use ist as sorting comparator. So if returned true the pairs will change place in array - like quicksort or so.
This offers us an option to sort non scalar types like virtual machine or other complex types.
Have a look at a workflow with VMs [Array/VirtualMachine] as input parameter - in this example my array contains 3 virtual machines:
The (partial) log shows this:
As you can see, the array is sorted ascending by the
id of each VM. If you want the array sorted ascending by
VM.name, try this (there are now 4 VMs in array):
And the log shows this:
Be careful with your self created sort function. Use it only on homogen arrays. Because all elements must support the properties you use in your function. On heterogen arrays adapt your function to match all possible elements.