2016-08-12 35 views
1

我正在尝试为javascript中的对象数组编写自定义排序功能。出于测试目的,我arr阵列看起来像这样:javascript中的自定义排序功能不起作用

[{ 
    _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

您的输入数组已经按照您的条件排序('numberOfVotes')。你期望会发生什么? – melpomene

+0

@melpomene我希望它被降序排序。如果我替换“<" with ">”,我收到相同的结果 – AvramPop

+2

尝试'arr.sort(function(a,b){return b.numberOfVotes - a.numberOfVotes;});'。 – melpomene

回答

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);

+0

我已经将此答案标记为正确,因为它更聪明,尽管理念是@melpomene的 – AvramPop

1

我想你想排序按降序排列。

您需要更改if block中的条件。还要注意像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