A fairly common thing is ranking an array of objects. A sort, followed by a map of the indexes is a simple way to do it.
However - when you have two values the same, you dont want the rank to be sequential. for example [10,11,20,20,24] ranks should be [0,1,2,2,4], whereas the above would give [0,1,2,3,4].
Here's a snippet in the useful library that's been generalized to produce proper rankings.
And here's how you would use it.
and the result
In some cases, the compare/getters/setters are fairly standard - so there are defaults as follows
So if your objects are in the right shape, you can just do this
and get this
In the examples so far, we'll get the original array back, sorted and ranked. However you may want to keep the original order and just attach ranks.
using the default setters/getters
gives this, retaining the original order
We've dealt with where we have an array of objects, and the the object gets populated with the rank. Lets say you have an array of primitives, and you want to rank, creating a new array of ranks, and retaining the original order. Here's an example using the default getters/setters
and the result - the ranks in the order of the input data
If you have some scripts you want add to this library, let me know on my forum.
You want to learn Google Apps Script?
Learning Apps Script, (and transitioning from VBA) are covered comprehensively in my my book, Going Gas - from VBA to Apps script, available All formats are available now from O'Reilly,Amazon and all good bookshops. You can also read a preview on O'Reilly.
Services > Desktop Liberation - the definitive resource for Google Apps Script and Microsoft Office automation > Google Apps Scripts snippets >