Issue429 Issue429 - 3 months ago 9
Javascript Question

Custom sorting function in javascript not working

I'm trying to write a custom sort function for my array of objects in javascript. For testing purposes, my

arr
array looks like this:

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


I want to sort the objects using this function(the criteria is
numberOfVotes
):

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


When i print the results, I receive the same order like before, aka
5798afda8830efa02be8201e,5798afad8830efa02be8201d


Am I missing something?

Answer

If you want to sort by descending order of votes:

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

Comments