在Javascript中对对象数组进行排序

时间:2015-07-07 13:16:49

标签: javascript arrays sorting

我有一个数组,每个元素都有两个属性:

var player = [{uid: 15, order: 567}, 
              {uid: 4, order: 789}, 
              {uid: 27, order: 123}, 
              {uid: 1, order: 654}];

我想按order属性对数组进行排序。结果将是:

player = [{uid: 27, order: 123},
          {uid: 15, order: 567},
          {uid: 1, order: 654},
          {uid: 4, order: 789}];

2 个答案:

答案 0 :(得分:0)

使用player.sort(function(d){ return d.order}) 的回调函数。

{{1}}

答案 1 :(得分:0)

var player = [{uid: 15, order: 567}, 
              {uid: 4, order: 789}, 
              {uid: 27, order: 123}, 
              {uid: 1, order: 654}];

player.sort(function(a,b){
   return a.order - b.order; 
});

JSFIDDLE.