2016-08-12 58 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