Javascript: sorting an array of objects by three values

跟風遠走 提交于 2021-02-07 08:54:46

问题


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.


回答1:


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




回答2:


Why so complicated? Try this:

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



回答3:


myArray.sort(function(a,b) {

    function getResult(first, second) {
      return (first < second) ? -1  : (first > second) ? 1 : 0;
    }

    if (a.Value1 !== b.Value1) return getResult(a.Value1, b.Value1);
    if (a.Value2 !== b.Value2) return getResult(a.Value2, b.Value2);
    return getResult(a.Value3, b.Value3);

 });



回答4:


For me this is more efficient and readable. On the other hand, it works for any number of fields

      List.sort(function (a, b) {
          var keyA = a.Field1;
          var keyB = b.Field1;

          if (keyA > keyB) return -1;
          if (keyA < keyB) return 1;

          keyA = a.Field2;
          keyB = b.Field2;

          if (keyA > keyB) return -1;
          if (keyA < keyB) return 1;

          keyA = a.Field3;
          keyB = b.Field3;

          if (keyA > keyB) return -1;
          if (keyA < keyB) return 1;

          //You can repeat this for any number of fields

          return 0;
      });


来源:https://stackoverflow.com/questions/13820759/javascript-sorting-an-array-of-objects-by-three-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!