Sort an object, then narrow down further - javascript

okay, so I have an object created as follows:

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 on.

Is there a way to sort these objects by day and then sort every day as a whole?

I am sure that you have many different ways to achieve this. Can anyone help with this? What would be the best way to do this?

+4
source share
1 answer

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!

+12
source

Source: https://habr.com/ru/post/1491960/


All Articles