我正在嘗試爲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
我錯過了什麼嗎?
您的輸入數組已經按照您的條件排序('numberOfVotes')。你期望會發生什麼? – melpomene
@melpomene我希望它被降序排序。如果我替換「<" with ">」,我收到相同的結果 – AvramPop
嘗試'arr.sort(function(a,b){return b.numberOfVotes - a.numberOfVotes;});'。 – melpomene