Re-implemented sortBy function.