views:

941

answers:

1

Hi,

i've built this sample code based on a real problem I have in an application. I've got a custom sort procedure to sort jQuery arrays. A container contains a list of items with special attributes.

For sorting:

  1. Loads all items in temp array
  2. Clears the container
  3. Sorts the temp array into a new array
  4. Append sorted items to container

Somehow Firefox knows how to sort but IE doesn't. Can somebody tell me what isn't working properly?

(you can copy-paste the html below into a empty .html file, it should work immediately)

<html>
<head>
<script type="text/javascript" 
    src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"&gt;&lt;/script&gt;
<script type="text/javascript">
    jQuery.fn.sort = function() {  
        return this.pushStack( [].sort.apply( this, arguments ), []);  
    } 

    function DoTheSort() {
        //Fetch elements in jQueryElement
        var sortableArray = $('#sortables').find('div.sortable');

        //Clear the sortables container
        $('#sortables').empty();

        //Sort the array
        var sortedArray = $(sortableArray).sort(sortProcedure);

        //Append sorted items
        jQuery.each(sortedArray, function() {
            alert($(this).attr("sortvalue"));
            $('#sortables').append(this);                
        });
    }

    function sortProcedure(a, b) {
    var value1 = parseInt($(a).attr("sortvalue"));
    var value2 = parseInt($(b).attr("sortvalue"));
        return value1 > value2;
    }


    </script>
</head>
<body>

    <a href="javascript:DoTheSort();">Sort</a>

    <div id="sortables">
        <div class="sortable" sortvalue="5">5</div>
        <div class="sortable" sortvalue="1">1</div>
        <div class="sortable" sortvalue="4">4</div>
        <div class="sortable" sortvalue="1">1</div>
        <div class="sortable" sortvalue="2">2</div>
        <div class="sortable" sortvalue="9">9</div>
        <div class="sortable" sortvalue="3">3</div>
    </div>



</body>
</html>
+4  A: 

Your sort procedure is subtly wrong: you need to account for equalities as well, and boolean is not the correct return type (see addendum).

Do this:

return value1 - value2;

instead of:

return value1 > value2;


Addendum:

The general form of a sort comparison function f(A,B) needs to return > 0 if A > B, < 0 if A < B, and 0 if no alteration needs to occur. Returning a boolean gets you caught by falsey values not representing what you think they do.

annakata
Great info! It didn't quite work in my application yet... I was putting the returned array (by the sort function) back in the same variable. This messed up things... Anyway got it to work now!
Ropstah
If this was not the solution, could you please explain how you fixed this error. I am having the same trouble.
Shiftbit