[SOLVED] Unexpected sort order results - can anyone explain why?

Another exercise, this time to demonstrate sort order on an array.

The array is: “Red”, " RED", “red”, “Green”, “Blue”

The expected result of the sort should have been: Blue,Green,RED,Red,red

But it’s coming out: RED,Blue,Green,Red,red

Can anyone give me a clue as to why that might be, as my understanding is that JS evaluates one character at a time to establish the sort order? It does the same in all the browsers I’ve tried.

function sortNums( x, y ) {
  return ( x - y );
}

function init() {
  var panel = document.getElementById( "panel" );
  var newPanel = "";
  var hues =  [ "Red", " RED", "red", "Green", "Blue" ];
  var nums = [ 1, 20, 3, 45, 44, 0.5 ];

  newPanel = "Colours: " + hues;
  newPanel += "<br>Dictionary sort: " + hues.sort();
  newPanel += "<hr>Numbers: " + nums;
  newPanel += "<br>Dictionary sort: " + nums.sort();
  newPanel += "<br>Numerical sort: " + nums.sort( sortNums );
  newPanel += "<br>Reversed: " + nums.reverse();

  panel.innerHTML = newPanel;

}
document.addEventListener( "DOMContentLoaded", init, false );

Check out Php ord(‘R’); and Php ord(‘E’); The results are lower than any lowercase value.

Pecked from a tablet :frowning:

Hey Chris,

var hues = [ “Red”, " RED", “red”, “Green”, “Blue” ];

You have a space before the word RED, which is causing it to be moved to the front of the sorted array.

3 Likes

You have no idea how long I’ve looked at that and never saw it - thanks!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.