Let's take a closer look at what @YuriyGalanter said. Let the small restructuring begin:
New structure
Modify the 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 } ];
Benefits of this approach
You get a few things with the above approach. For one, readability. It is much easier to read and understand where each object begins and ends, and understand which objects cover which properties. Secondly, this will make JavaScript sorting easy. The built-in .sort() function can take an optional parameter - A Function -, which defines a custom sorting algorithm for the absence of a better word. Let's take a look at this:
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 sorting algorithm can be extended by simply adding the following sorting criteria instead of return 0; and continuing. This should help you get started in the right direction.
Good luck and happy coding!
source share