0

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);
4
  • Ok, you have comparer. How did you use it in order to sort? Commented Aug 21, 2011 at 22:45
  • example provided by edit of original post Commented Aug 21, 2011 at 22:52
  • I see you sort by wigetID instead of widgetId. Could your problem be caused by this typo? Commented Aug 21, 2011 at 22:56
  • I could see where you might think that, unfortunately in the original JSON string that typo is actually legitimate. But the sources creating said JSON initially are from a JAVA level infrastructure so that portion is out of my control gotta work with what I get ya know. Commented Aug 21, 2011 at 23:00

1 Answer 1

1

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

You can simplify that sort function, and just return parseInt(a.wigedID, 10) - parseInt(b.wigedID, 10).
If the incoming values are known to be digits, there's no need for parseInt, the subtraction operator (-) will convert strings to numbers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.