I have an array of objects like this:-
var arr = [ {total : 20, name: David},
{total : 10, name: Joe},
{total : 15, name: Tracy},
{total : 20, name: Joel},
{total : 15, name: Michael},
{total : 10, name: Arnold},
{total : 15, name: Paul},
]
I need to sort them first by total and then if the total of two are the same I need to sort them by name
My expected outcome after sort should be as follows:
var arr = [ {total : 20, name: David},
{total : 20, name: Joel},
{total : 15, name: Michael},
{total : 15, name: Paul},
{total : 15, name: Tracy},
{total : 10, name: Arnold},
{total : 10, name: Joe},
]
Can anyone tell me how to sort it using Array.sort()?
You could chain the sort criteria with logical OR and use a delta for total and String#localeCompare for name.
// Sort by total then name.
var array = [
{total: 20, name: 'David'},
{total: 10, name: 'Joe'},
{total: 15, name: 'Tracy'},
{total: 20, name: 'Joel'},
{total: 15, name: 'Michael'},
{total: 10, name: 'Arnold'},
{total: 15, name: 'Paul'}
];
array.sort(function (a, b) {
return b.total - a.total || a.name.localeCompare(b.name);
});
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With