Thread: Ranking Array

    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2008
    Posts
    28
    Rep Power
    0

    Ranking Array


    I'm new to programming and trying to figure out how to rank on more then one criteria.

    There are lots of simple examples of doing this based on value, but I haven't found one that evaluates on more then one criteria item.


    The ranking criteria is by first "Priority" (#1 - Urgent, #2 Regular") then by Date ASC order.

    myArray: [
    {item: "Box", priority: "Urgent", orderDate: "1/2/2013'},
    {item: "Stick", priority: "Regular", orderDate: "2/8/2012'},
    {item: "Ball", priority: "Urgent", orderDate: "1/1/2013'}
    ];


    After Ranking
    myArray: [
    {item: "Ball", priority: "Urgent", orderDate: "1/1/2013'},
    {item: "Box", priority: "Urgent", orderDate: "1/2/2013'},
    {item: "Stick", priority: "Regular", orderDate: "2/8/2012'}
    ];
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2013
    Posts
    101
    Rep Power
    27
    You can use the native Array.prototype.sort() to sort by a comparator that takes into account a primary, then secondary, sorting parameter. You write the comparator as a function that takes two arguments, a and b, and returns a negative value if "a" comes first, positive value if "b" comes first.
    Code:
    myArray.sort(function (a, b) {
        // if a.priority and b.priority are equal then compare by orderDate
        if (a.priority == b.priority) {
            return (a.orderDate < b.orderDate ? -1 : 1); // Just for example, need to do this better
        }
        // sort by priority
        // lazily assume that since the priority values differ, and there are only two possible 
        // priority values, than if a.priority is Urgent then it comes first; otherwise b comes first
        if ("Urgent" == a.priority) return -1;
        else return 1;
    });
    I wrote a very bad equality there for the orderDate values - you should convert the strings to Date, probably, then compare them. As written I doubt it works right. But hopefully you get the idea.

IMN logo majestic logo threadwatch logo seochat tools logo