Backend implementation of sorting, javascript refactored