red888
red888

Reputation: 31570

Sorting an array of divs by their ID values

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);
}

Upvotes: 0

Views: 121

Answers (1)

Alex
Alex

Reputation: 61

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

Upvotes: 1

Related Questions