Groovy sorting by multiple properties:

http://www.tothenew.com/blog/groovier-way-of-sorting-over-multiple-fields-in-a-list-of-maps-in-groovy/

List list = [
    [id:0, firstName: 'Sachin', lastName: 'Tendulkar', age: 40 ],
    [id:1, firstName: 'Sachin', lastName: 'Tendulkar', age: 103 ],
    [id:2, firstName: 'Ajay', lastName: 'Tendulkar', age: 48 ],
    [id:3, firstName: 'Virendra', lastName: 'Sehwag', age: 5 ],
    [id:4, firstName: 'Virendra', lastName: 'Sehwag', age: 50 ],
    [id:5, firstName: 'Sachin', lastName: 'Nayyar', age: 15 ]
]

def ids = list.sort { a,b ->
   a.firstName <=> b.firstName ?: a.lastName <=> b.lastName ?: a.age <=> b.age
}*.id

assert ids == [2, 5, 0, 1, 3, 4]

 

Javascript sorting by multiple properties:

http://stackoverflow.com/questions/9175268/javascript-sort-function-sort-by-first-then-by-second

objects = []
object[0] = {strength: 3, name: "Leo"}
object[1] = {strength: 3, name: "Mike"}

function cmp(a, b) {
    if (a > b) return +1;
    if (a < b) return -1;
    return 0;
}
array.sort(function(a, b) {
    return cmp(a.strength,b.strength) || cmp(a.name,b.name)
})
Advertisements