javascript中的自定义排序功能无法正常工作

时间:2016-08-12 09:30:10

标签: javascript arrays function sorting object

我正在尝试在javascript中为我的对象数组编写自定义排序函数。出于测试目的,我的arr数组如下所示:

[{
  _id: '5798afda8830efa02be8201e',
  type: 'PCR',
  personId: '5798ae85db45cfc0130d864a',
  numberOfVotes: 1,
  __v: 0
}, {
  _id: '5798afad8830efa02be8201d',
  type: 'PRM',
  personId: '5798aedadb45cfc0130d864b',
  numberOfVotes: 7,
  __v: 0
}]

我想使用此功能对对象进行排序(条件为numberOfVotes):

arr.sort(function(a, b) {
  if (a.numberOfVotes > b.numberOfVotes) {
    return 1;
  }
  if (b.numberOfVotes > a.numberOfVotes) {
    return -1;
  } else return 0;
});

当我打印结果时,我会收到与之前相同的订单,即5798afda8830efa02be8201e,5798afad8830efa02be8201d

我错过了什么吗?

2 个答案:

答案 0 :(得分:2)

如果您想按投票顺序排序:



var arr = [{_id: '5798afda8830efa02be8201e',type: 'PCR',personId: '5798ae85db45cfc0130d864a',numberOfVotes: 1,__v: 0}, {_id: '5798afad8830efa02be8201d',type: 'PRM',personId: '5798aedadb45cfc0130d864b',numberOfVotes: 7,__v: 0}];

arr.sort(function(a, b) {
  return b.numberOfVotes - a.numberOfVotes;
});

console.log(arr);




答案 1 :(得分:1)

我想你想按投票顺序排序。

您需要更改if块中的条件。另请注意,5798afda8830efa02be8201e之类的ID是错误的,它必须是字符串'5798afda8830efa02be8201e'



    var arr=[{
      _id: '5798afda8830efa02be8201e',
      type: 'PCR',
      personId: '5798ae85db45cfc0130d864a',
      numberOfVotes: 1,
      __v: 0
    }, {
      _id: '5798afad8830efa02be8201d',
      type: 'PRM',
      personId: '5798aedadb45cfc0130d864b',
      numberOfVotes: 7,
      __v: 0
    }]
    
    arr.sort( function ( a, b ) {
          if ( a.numberOfVotes < b.numberOfVotes ) {
            return 1;
          }
          else if ( b.numberOfVotes < a.numberOfVotes ) {
            return -1;
          } else{return 0;}
       });
    
    console.log(arr)
&#13;
&#13;
&#13;

JSFIDDLE