【问题标题】:Custom sorting function in javascript not workingjavascript中的自定义排序功能不起作用
【发布时间】:2016-12-19 06:25:15
【问题描述】:

我正在尝试为我的 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

我错过了什么吗?

【问题讨论】:

  • 您的输入数组已按您的条件排序 (numberOfVotes)。你预计会发生什么?
  • @melpomene 我希望它降序排序。如果我用“>”替换“
  • 试试arr.sort(function (a, b) { return b.numberOfVotes - a.numberOfVotes; });
  • @Issue429 如果你把两个符号都改成
  • @Issue429 所以显示你的实际代码。

标签: javascript arrays function sorting object


【解决方案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)

JSFIDDLE

【讨论】:

    【解决方案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);

    【讨论】:

    • 我已将此答案标记为正确,因为它更聪明,即使想法是 @melpomene 的
    猜你喜欢
    • 2016-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-27
    • 1970-01-01
    • 2018-04-04
    • 2011-11-01
    • 1970-01-01
    相关资源
    最近更新 更多