Reputation: 59
I am using javascript sort method. I want to sort the doc_requirement key of items in order 1,4,3,0 But the order I am getting is 4,3,1,0 . How to achieve a particular order rather than sorting in ascending or descending manner?
var items = [
{ doc_requirement :4},
{ doc_requirement: 3 },
{ doc_requirement:3 },
{doc_requirement: 0 },
{ doc_requirement: 1 },
{ doc_requirement: 3 }
];
items.sort(function(firstDoc, secondDoc) {
if(firstDoc.doc_requirement < secondDoc.doc_requirement){
return true;
} else if(firstDoc.doc_requirement == secondDoc.doc_requirement){
return true;
} else{
return false;
}
});
Output expected
var items =[ { doc_requirement: 1 },
{ doc_requirement: 4 },
{ doc_requirement: 3 },
{ doc_requirement: 3 },
{ doc_requirement: 3 },
{ doc_requirement: 0 } ]
Upvotes: 0
Views: 44
Reputation: 4378
Your sort function should return integers, not booleans (Source: Array.prototype.sort()). It should look like this:
function compare(a, b) {
if (a is less than b by some ordering criterion) {
return -1;
}
if (a is greater than b by the ordering criterion) {
return 1;
}
// a must be equal to b
return 0;
}
In your case, you could use this:
function compare(a, b) {
var order = [1, 4, 3, 0];
var i1 = order.indexOf(a.doc_requirement);
var i2 = order.indexOf(b.doc_requirement);
return i1 - i2;
}
Upvotes: 3