Jump to content

Localecompare()?


tinfanide

Recommended Posts

		<script type="text/javascript">	  			function generateCompareTRs(iCol) {	  				return  function compareTRs(oTR1, oTR2) {							var sValue1 = oTR1.cells[iCol].firstChild.nodeValue;							var sValue2 = oTR2.cells[iCol].firstChild.nodeValue;	  							return sValue1.localeCompare(sValue2);						};			}		  			function sortTable(sTableID, iCol) {				var oTable = document.getElementById(sTableID);				var oTBody = oTable.tBodies[0];				var colDataRows = oTBody.rows;				var aTRs = new Array;	  				for (var i=0; i < colDataRows.length; i++) {					aTRs[i] = colDataRows[i];				}	  				if (oTable.sortCol == iCol) {					aTRs.reverse();				} else {					aTRs.sort(generateCompareTRs(iCol));				}	  				var oFragment = document.createDocumentFragment();				for (var i=0; i < aTRs.length; i++) {					oFragment.appendChild(aTRs[i]);				}	  				oTBody.appendChild(oFragment);				oTable.sortCol = iCol;			}  		</script>

I have no idea why

return sValue1.localeCompare(sValue2);

is needed? I know strings are to be compared to sort the order and it returns -1, 0 or 1. But why those results are needed in this line:

aTRs.sort(generateCompareTRs(iCol));

Link to comment
Share on other sites

Well, the localCompare() method checks whether another string comes "before" or "after" the string. Then it is used to sort the array of rows. Do you understand how the sort() method works? It takes one parameter, that being a function with two parameters. It then calls that function with each pair of elements in turn to determine the sort order.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...