Javascript:按三个值对对象数组进行排序 [英] Javascript: sorting an array of objects by three values

查看:71
本文介绍了Javascript:按三个值对对象数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象数组,我想使用.sort()函数进行排序.它应按三个值排序(第一个按第一个值排序,然后按第二个按值排序,最后按第三个按值排序).我已经尝试过类似以下的方法,但是它似乎无法正常工作.

  myArray.sort(function(a,b){如果(a.Value1 === b.Value1){如果(a.Value2 === b.Value2){返回(a.Value3< b.Value3)吗?-1:(a.Value3> b.Value3)?1:0;} 别的 {返回(a.Value2< b.Value2)吗?-1:1;}} 别的 {如果(a.Value2 === b.Value2){return(a.Value1< b.Value1)吗?-1:1;} 别的 {返回(a.Value2< b.Value2)吗?-1:1;}}}); 

任何帮助将不胜感激.

解决方案

这通常很好,但是在 a.Value1!== b.Value1 的琐碎情况下,您搞砸了逻辑./p>

这是固定版本:

  myArray.sort(function(a,b){如果(a.Value1 === b.Value1){如果(a.Value2 === b.Value2){返回(a.Value3< b.Value3)吗?-1:(a.Value3> b.Value3)?1:0;} 别的 {返回(a.Value2< b.Value2)吗?-1:1;}} 别的 {返回(a.Value1< b.Value1)吗?-1:1;}}); 

演示

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.

解决方案

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

这篇关于Javascript:按三个值对对象数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆