Reputation: 3827
This should be a super simple thing, but I am having an issue working this out. I am trying to implement a sort to move all of one type of objects to the top of a list. For example, a list of tasks, I would like to sort it so all the tasks of a particular owner appear at the top of the list. This is what I have now:
this.sortByOwner = function(owner) {
return tasks.sort(function(a, b) {
var nameA = a.ownerUser.displayName.toLowerCase();
var nameB = b.ownerUser.displayName.toLowerCase();
var displayName = owner.displayName.toLowerCase();
if (nameA == displayName) //sort string descending
return -1;
else if (nameA == "")
return 1;
return 0; //default return value (no sorting)
});
};
but this doesn't work quite right. They do appear to be grouping the tasks, but unfortunately, the users tasks are not appearing at the top. What I would expect to see is the tasks that are owned by the specific person would appear at the top. What am I doing wrong here?
Including a basic JSFiddle example: http://jsfiddle.net/zJwUn/5/
Upvotes: 1
Views: 132
Reputation: 11238
You're missing at least one check, the case where nameB is the owner.
here's a fixed version from your fiddle
function sortByOwner(owner) {
return tasks.sort(function (a, b) {
var nameA = a.displayName.toLowerCase(),
nameB = b.displayName.toLowerCase();
var displayName = owner.displayName.toLowerCase();
if (nameA === nameB) return 0;
if (nameA == displayName) //sort string descending
return -1;
if (nameB == displayName)
return 1;
// at this point neither A or B are the owner
if (nameA == "") return 1;
if (nameB == "") return -1;
return 0 //default return value (no sorting)
})
}
Upvotes: 2
Reputation: 229501
You didn't handle the case where nameB
is the displayName
. This works for me:
function sortByOwner(owner) {
return tasks.sort(function(a, b){
var nameA=a.displayName.toLowerCase(), nameB=b.displayName.toLowerCase();
var displayName = owner.displayName.toLowerCase();
if (nameA == displayName) //sort string descending
return -1;
if (nameA == "")
return 1;
if (nameB == displayName) //sort string descending
return 1;
if (nameB == "")
return -1;
return 0; //default return value (no sorting)
})
}
Upvotes: 4