0

I have a list of divs that I would like to sort by their ID values. The problem is that the IDs are values like this: "indexNumber123".

I would like to sort them "numerically" as in "indexNumber1","indexNumber2","indexNumber3" to reorder them before displaying their HTML.

The code base for this application is a sloppy mess so I thought I could just get away with doing this via DOM manipulation with jquery and just be done with it.

I tried to do this by getting an array of the divs and then passing a compare function to the sort method of the array. I thought I could parse the ID values in the compare method and compare the numeric values, but this is not sorting them correctly.

function compare(a,b) {

    var aId = parseInt(a.id.replace( /^\D+/g, ''));
    var bId = parseInt(b.id.replace( /^\D+/g, ''));

    if (aId < bId)
        return -1;
    if (aId > bId)
        return 1;
    return 0;
}

//fired on a button click
function sortNumeric() {
        var arrDivs = [];

        $('[id^="indexNumber"]').each(
            function() {
                arrDivs.push($(this)[0]);
            });

        var sortedDivs = arrDivs.sort(compare);
        console.dir(sortedDivs);
}
red888
  • 18,164
  • 26
  • 123
  • 237
  • Can you post a simple fiddle to demonstrate? – Matt Burland Aug 06 '14 at 17:16
  • 1
    Please show some example markup for the divs, and how they don't "sort correctly". Also, where are you displaying them? You currently are only sorting the jQuery collection. – Bergi Aug 06 '14 at 17:28

1 Answers1

1
function compare(a,b) {

    var aId = parseInt(a.id.replace( /^\D+/g, ''));
    var bId = parseInt(b.id.replace( /^\D+/g, ''));

    return +aId - +bId
}

//fired on a button click
function sortNumeric() {
        var arrDivs = $('[id^="indexNumber"]'), 
            sortedDivs = arrDivs.sort(compare);

        console.dir(sortedDivs);
}

Try this. you probably need to convert "stringID" to NumberID

Alex
  • 61
  • 4
  • YESSSS that works perfectly, but why? Why was my code not working and what exactly is +aId - +bId? Thanks a bunch. – red888 Aug 06 '14 at 17:47
  • 1
    The Unary +/- operator converts its operand to Number type. http://stackoverflow.com/questions/5450076/whats-the-significant-use-of-unary-plus-and-minus-operators – Alex Aug 06 '14 at 18:03
  • 1
    So parseInt() wasn't converting it to an int? – red888 Aug 06 '14 at 18:16
  • Why not? parseInt will get the same result as the unary+ for integer – Alex Aug 06 '14 at 18:27