I am having trouble sorting an array that includes undefined elements (a sparse array) in IE7. This works great in Safari and Firefox of course, and I haven't tried other versions of IE, but here is a simple example.
<html>
<head>
<script type="text/javascript">
function runscript() {
var myArray = [{id: 2},
undefined,
{id: 0},
{id: 1},
{id: 3},
{id: 4},
{id: 5}];
myArray.sort(function compare(a, b) { return a.id - b.id; });
var output = '';
for (loop in myArray) {
output += myArray[loop].id + ' ';
}
alert(output);
}
</script>
</head>
<body onLoad="runscript();">
</body>
The alert() at the end inexplicably shows 0 2 3 4 5 1. Removing the undefined element from the array correctly sorts it and the alert shows 0 1 2 3 4 5.
Is there a way to work around this in IE7 so that I can reliably sort arrays that include undefined elements? I don't care where the undefined elements end up as long as the defined elements are sorted correctly.