numbas / Numbas

A completely browser-based e-assessment/e-learning system, with an emphasis on mathematics
http://www.numbas.org.uk
Apache License 2.0
203 stars 118 forks source link

Add 'sort_by' JME built-in, to sort list elements by a given key #530

Closed christianp closed 5 years ago

christianp commented 6 years ago

I've made an example at https://numbas.mathcentre.ac.uk/question/32877/sort-a-list-of-lists-by-a-particular-key/. See the definition of sort_by in the Extensions tab.

If the index parameter is a string, it could also sort dictionaries by key. A more adventurous version would take an expression to evaluate for each item, in the manner of map.

To do this, add a function sort_by to runtime/scripts/jme-builtin.js, with the function body taken from the question linked above, and otherwise following the definition of sort. Remember to change the signature to take a TNum or TString parameter before the TList; for clarity, it's probably worth defining a version for each of these cases. You could ideally also define a custom typecheck function which makes sure that each element of the list is of the right type and has the given key.

christianp commented 6 years ago

group_by would also be nice.