arrays - Javascript - Group by one property, sort by another -


i have array of objects, , have them sorted 1 property (a number). have sort button allow user sort them attribute (a string). how can sort them specific value, , keep them in order of number sort in javascript?

a quick example, using person name, age, , favorite color:

steve, 27, blue joe, 28, red john, 30, green jane, 33, blue julie, 35, blue kevin, 40, red 

so, if user wanted sort list people favorite color of red, i'd want show this:

joe, 28, red kevin, 40, red steve, 27, blue jane, 33, blue julie, 35, blue john, 30, green 

the order of property after selected 1 doesn't matter, long grouped , sorted age. example, above list (sorted red) have john listed after kevin, long steve, jane , julie stayed in same order.

basically, want group by string, , sort group number.

thank help!

sounds you're trying order (color = red), color, age (not sql syntax): first red, grouped color, age per group.

that's tricky in 1 sorter...

i think one:

function(a, b) {     if (a.color == 'red') {         if (b.color == 'red') {             // both red, check age             return a.age - b.age;         }         // red, top         return -1;     }      if (b.color == 'red') {         // b red, top         return 1;     }      if (a.color == b.color) {         // same color, check age         return a.age - b.age;     }      // different color, check     return a.color < b.color ? -1 : 1; } 

result seems it:

joe     28  red kevin   40  red steve   27  blue jane    33  blue julie   35  blue john    30  green 

maybe could've been shorter, can't think anymore.

demo on http://jsfiddle.net/rudiedirkx/83sm2squ/


Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -