1

I'm trying to do a client-side sort of a jQuery UI accordion, to place the accordion sections in alphabetical order by header text.

The jQuery UI structure consists of an h3 for the category header, and a following div for the contents of that category. Therefore, I need to sort on the h3 text, but move each h3 and its following div in tandem in the DOM.

I have the following functions that work in FF and Chrome, but not in any flavor of IE:

function sort_accordion_headers() {
    var tempArray = [];
    //Push h3-div pairs into array
    $('.accordion h3').each(function(i,ui) {
        tempArray.push(new accordion_sort_object(ui,$(ui).next('div')));
    });
    //Sort the array on header text
    tempArray.sort(function(a,b) {
                var keyA = $(a.header).text();
                var keyB = $(b.header).text();
                return (keyA > keyB) ? 1 : 0;   
    });
    //Clear accordion contents and replace with re-sorted content
    for (var i in tempArray) {
        $('.accordion').append(tempArray[i].header).append(tempArray[i].div); 
    }
}

//Creates custom object for sorting accordion headers
function accordion_sort_object($htag,$div) {
    this.header = $htag;
    this.div = $div;
}

Any idea why this doesn't work in IE? It feels like it must be something to do with the append() or sort() functions, but I'm not sure what.

Edit: To clarify, it doesn't throw errors in IE; it just doesn't perform the sort. The accordion sections remain in their original order.

Edit: Problem solved! Thanks to Plalx for pointing out that I was returning 0 when KeyA was less than KeyB, when I should have been returning -1.

Steve Ray
  • 158
  • 8
  • http://stackoverflow.com/questions/2956432/js-sort-works-in-firefox-but-not-ie-cant-work-out-why ? – kieran May 09 '13 at 02:20
  • 1
    It's probably not your issue, however you should not use a `for in` construct to loop over an array. See [this question](http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-such-a-bad-idea) – plalx May 09 '13 at 02:22
  • Is it possible that the array _is_ being sorted, but your reinsertion code isn't working? Perhaps a breakpoint after the sort would be a good idea to see whether the array has been sorted – Simon MᶜKenzie May 09 '13 at 02:28

1 Answers1

2

The sort method sorts the Array object in place; no new Array object is created during execution. If you supply a function in the sortFunction argument, it must return one of the following values:

  • A negative value if the first argument passed is less than the second argument.
  • Zero if the two arguments are equivalent.
  • A positive value if the first argument is greater than the second argument.

Taken from http://msdn.microsoft.com/en-us/library/ie/4b4fbfhk(v=vs.94).aspx

['b', 'a'].sort(function (a, b) { return a > b? 1 : (b > a? -1 : 0) }); //a, b
plalx
  • 42,889
  • 6
  • 74
  • 90