How to sort array with undefined elements in IE7 JavaScript

Posted by Gene Goykhman on Stack Overflow See other posts from Stack Overflow or by Gene Goykhman
Published on 2010-05-21T07:19:32Z Indexed on 2010/05/21 10:10 UTC
Read the original article Hit count: 211

Filed under:
|

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.

© Stack Overflow or respective owner

Related posts about ie7

Related posts about JavaScript