While using sort() method in Javascript, I'm not able to correctly sort an array of more than 10 objects. This happens only in Google Chrome; with Firefox and IE it works.
I have an array of 11 objects with two properties, number and name; I'd like to order these object per number and then per name, but with Chrome it doesn't work.
This is the code of the whole page:
<!DOCTYPE html>
<HTML>
<HEAD>
<SCRIPT>
var availableTags = [
{number: 0,name:"Consigli"},
{number: 0,name:"De sanctis"},
{number: 0,name:"Perin"},
{number: 1,name:"Bonucci"},
{number: 2,name:"Essien"},
{number: 2,name:"Florenzi"},
{number: 2,name:"Hernanes"},
{number: 2,name:"Martinho"},
{number: 2,name:"Montolivo"},
{number: 2,name:"Parolo"},
{number: 2,name:"Perez"}
];
function sortPlayers(a, b) {
var result = (parseInt(a.number) > parseInt(b.number));
if( (!result) && (parseInt(a.number) == parseInt(b.number)) ) {
result = a.name.toLowerCase().localeCompare(b.name.toLowerCase());
}
return result;
}
function updateFormation() {
availableTags.sort( sortPlayers );
var html = "";
for (var i = 0; i < availableTags.length; i++) {
html += availableTags[i].number + " " + availableTags[i].name + "\n";
}
alert(html);
}
</SCRIPT>
</HEAD>
<BODY>
<script type="text/javascript">
updateFormation();
</script>
</BODY>
At the following link: http://blog.rodneyrehm.de/archives/14-Sorting-Were-Doing-It-Wrong.html I read that "Chrome will sort arrays using InsertionSort if the array has 10 or less elements.": maybe this may help...
Does anybody can help me?