Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform a JavaScript Sort() with a Then-By

Tags:

javascript

I have an array full of objects which need to be sorted, however I cannot seem to get this working. Normally I would just do a simple sort() method, which works fine for sorting on a single column, however in this case I need to sort by one column and then by a second.

To try make this easier to understand, let's say I have an array of objects similar to this one:

{ Name: 'Alfred', Total: 4, Project: 'Foobar' }

Now in this example, how would I go about sorting an array of these objects first by Name, and then by Total? I considered doing something like this:

myArray = myArray.sort(function(a,b){return (a.Name + a.Total) > (b.Name + b.Total)});

However I am not sure what is the best method to approach this. Some suggestions would be appreciated.

like image 602
JustinN Avatar asked Oct 31 '25 09:10

JustinN


2 Answers

myArray.sort(function(a,b){
  if(a.Name>b.Name){return 1;}
  else if(a.Name<b.Name){return -1;}
  else{
    if(a.Total>b.Total) return 1;
    else if(a.Total<b.Total) return -1;
    else return 0;
  }
});

Minified version:

myArray.sort(function(a,b){return a.Name>b.Name?1:a.Name<b.Name?-1:a.Total>b.Total?1:a.Total<b.Total?-1:0});
like image 124
Passerby Avatar answered Nov 02 '25 00:11

Passerby


myArray = myArray.sort(function(a, b) {
  var ret = a.Name.localeCompare(b.Name);
  if (ret == 0) {
     if (a.Total > b.Total) {
         return 1;
     } else if (a.Total < b.Total) {
         return -1;
     }
  }
  return ret; 
});
like image 39
xdazz Avatar answered Nov 01 '25 22:11

xdazz



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!