chris
chris

Reputation: 36957

Sorting JSON Object via JavaScript odd results

Alright Odd results, not so much as they are expected. However I'm not sure how to over come it, I am having one of those days where every logical thing is the equivalent of a massive brain fart for me. Anyway. Lets say for the sake of ease. My array is numeric only nothing else in there.. My array ranges from 1-50 so my results upon sorting it are similar to 1, 10, 11, 12, 13.... 2, 20, 21, 22, 23... etc. When I need it to go like 1,2,3,4,5,6,7,8,9,10,11,12...

My simple little canned function is..

function sortJSONresultsByWidgetID(a,b)
{   
    if(parseInt(a.wigetID) == parseInt(b.wigetID))
    {
        return 0;
    }
    return parseInt(a.wigetID) > parseInt(b.wigetID) ? 1 : -1;
}

for reference I parseInt due to the JSON the way my JSON handles when I post it back and forth from the DB, I store the actual JSON in the DB and when passing it to the PHP it wraps quotes around the number turning them from INT to string (or from what I notice that may be browser based).

So here I am stuck now cause I want these things listed in a particular order and my brain wont work today.

EDIT example of me sorting results:

dashboardJSON.widgets.sort(sortJSONresultsByWidgetID);

Upvotes: 0

Views: 458

Answers (1)

nickytonline
nickytonline

Reputation: 6981

You need to parse the ints with a radix of 10 and use the === operator instead of ==. I think that should do it.

function sortJSONresultsByWidgetID(a,b)
{
    var widgetAId = parseInt(a.wigetID, 10);
    var widgetBId = parseInt(b.wigetID, 10);

    if(widgetAId === widgetBId)
    {
        return 0;
    }
    return widgetAId > widgetBId ? 1 : -1;
}

UPDATE - Here's with Ellian's optimization:

function sortJSONresultsByWidgetID(a,b)
{
    return parseInt(a.wigetID, 10) - parseInt(b.wigetID, 10);
}

Upvotes: 1

Related Questions