jquery - sort object then subsort further - javascript -


okay have object created 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 fourth.

is there way sort these objects day, , sort each day total?

i'm sure theres multiple different ways achieve this. 1 this? best way it?.

let's take more in-depth @ @yuriygalanter said. let's begin little restructuring:

new structure

modify old object 9 properties array containing 3 objects 3 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 approach

you gain few things having above approach. one, readability. easier read , understand each object begins , ends , understand objects encompass properties. secondly, going make sorting javascript breeze. built in .sort() function can take optional parameter - function - defines custom sort "algorithm" lack of better word. let's take @ 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 days same,         // 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 extended, adding next sort criteria in place of return 0; , continuing on. should started in right direction.

good luck , happy coding!


Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -