Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort object then subsort further - javascript [closed]

okay so i have an object created like this:

object = {};

object.set_1.date = <date object or unix time stamp>
object.set_1.day = "Sunday";
object.set_1.total = 12;

object.set_2.date = <date object or unix time stamp>
object.set_2.day = "Sunday";
object.set_2.total = 19;

object.set_3.date = <date object or unix time stamp>
object.set_3.day = "Monday";
object.set_3.total = 15;

and so fourth.

Is there a way to sort these objects by day, and then sort each day by total?

I'm sure theres multiple different ways to achieve this. Could any one help with this? what would be the best way to do it?.

like image 815
Dustin Silk Avatar asked Jul 17 '13 19:07

Dustin Silk


1 Answers

Let's take a more in-depth look at what @YuriyGalanter said. Let's begin with a little restructuring:

New Structure

Modify your old object with nine properties to be an array containing three objects with three properties:

objArray = [
    {
        "date": <date object or unix time stamp>,
        "day": "Sunday",
        "total": 12
    },
    {
        "date": <date object or unix time stamp>,
        "day": "Sunday",
        "total": 19
    },
    {
        "date": <date object or unix time stamp>,
        "day": "Monday",
        "total": 15
    }
];

Advantages of this Approach

You gain a few things by having the above approach. For one, readability. It is much easier to read and understand where each object begins and ends and to understand which objects encompass which properties. Secondly, this is going to make sorting with JavaScript a breeze. The built in .sort() function can take an optional parameter - A Function - that defines a custom sort "algorithm" for lack of a better word. Let's take a look at that:

Custom JavaScript Sort

objArray.sort(function (objA, objB) {
    var dayA = (objA.day).toLowerCase();
    var dayB = (objB.day).toLowerCase();

    // Sort first on day
    if(dayA > dayB) {
        return 1;
    } else if (dayA < dayB) {
        return -1;
    } else {
        // If the days are the same,
        // do a nested sort on total.
        var totalA = objA.total;
        var totalB = objB.total;

        if(totalA > totalB) {
            return 1;
        } else if (totalA < totalB) {
            return -1;
        } else {
            return 0;
        }
    }
});

The above nested sort algorithm can be extended, simply by adding your next sort criteria in place of the return 0; and continuing on. This should get you started in the right direction.

Good luck and happy coding!

like image 179
War10ck Avatar answered Nov 05 '22 00:11

War10ck