sort available values in wp modals

https://www.openproject.org/work_packages/16199

I notice that what I am doing is quite repetitive. Asking as a noob here: How can I share the code better?