Add undefined check to sorting