Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple sort in JavaScript

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()?

like image 859
Manish Poduval Avatar asked Apr 05 '26 16:04

Manish Poduval


1 Answers

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; }
like image 144
Nina Scholz Avatar answered Apr 08 '26 05:04

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!