Ukuser32
Ukuser32

Reputation: 2189

Microsoft Edge and Sorting with jQuery

I have the following code which works fine with Firefox and Chrome, but with Microsoft Edge (default settings) the list items are not sorted — they are left unordered. I'm using MS Edge 20.10240.16384.0.

Has anyone seen this problem and found a solution? (id here is the container of the ul)

$( id + ' li' ).sort(function ( a, b ) {
    return parseFloat( $( a ).attr( "id" ).replace( 'page', '' ) )
         > parseFloat( $( b ).attr( "id" ).replace( 'page', '' ) );
}).appendTo( id + ' ul' );

JS fiddle example: https://jsfiddle.net/c1d8caa5/2/

Upvotes: 4

Views: 574

Answers (1)

Sampson
Sampson

Reputation: 268364

This code leverages the native Array.prototype.sort method, which is described in section 22.1.3.24 of the ECMAScript standard. This method accepts a single comparefn argument:

If comparefn is not undefined, it should be a function that accepts two arguments x and y and returns a negative value if x < y, zero if x = y, or a positive value if x > y. (emphasis added)

As such, make sure your compare function returns either -1, 0, or 1. Additionally, you can subtract one number from the other, which will yield a negative number, zero, or a positive number, and thus fulfilling the requirements.

While Microsoft Edge may not be in violation of the standard here, if other major browsers implement this more loosely (accepting Booleans), and Edge does not, this may be grounds to file an interop issue and see if Edge should be brought into alignment.

I work on the Edge team, and will file an issue for consideration.

Upvotes: 3

Related Questions