Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: sorting an array of objects by three values

I have an array of objects that I would like to sort using the .sort() function. It shall be sorted by three values (first by the first value, then by the second and finally by the third). I have tried something like the following but it doesn't seem to work properly.

myArray.sort(function(a,b) {
     if (a.Value1 === b.Value1) {
         if (a.Value2 === b.Value2) {
             return (a.Value3 < b.Value3) ? -1 : (a.Value3 > b.Value3) ? 1 : 0;
         } else {
             return (a.Value2 < b.Value2) ? -1 : 1;
         }
     } else {
         if (a.Value2 === b.Value2) {
             return(a.Value1 < b.Value1) ? -1 : 1;
         } else {
             return (a.Value2 < b.Value2) ? -1 : 1;
         }
     }
 });

Any help will be appreciated.

like image 972
Fantaftw Avatar asked Oct 25 '25 16:10

Fantaftw


1 Answers

It was mostly good but you messed up the logic in the trivial case where a.Value1 !== b.Value1.

Here's a fixed version :

myArray.sort(function(a,b) {
     if (a.Value1 === b.Value1) {
         if (a.Value2 === b.Value2) {
             return (a.Value3 < b.Value3) ? -1 : (a.Value3 > b.Value3) ? 1 : 0;
         } else {
             return (a.Value2 < b.Value2) ? -1 : 1;
         }
     } else {
          return (a.Value1 < b.Value1) ? -1 : 1;
     }
});

Demonstration

like image 62
Denys Séguret Avatar answered Oct 28 '25 05:10

Denys Séguret