Added check to determine if sort is undefined before running the sorting direction logic