I'm using an array sorting function with my AngularJS app. It uses a variable, direction
, to determine whether to sort the data in an ascending (direction === -1
) or descending (direction === 1
) manner.
What's going wrong: Sometimes when I do a sort, elements in the array which should be in the same position are returned in a different position, without anything in the array actually changing.
For instance, if I have:
var arr = [
{id: 3, name: 'd'},
{id: 2, name: 'b'},
{id: 1, name: 'a'},
{id: 2, name: 'c'}
];
and I sort it by "id" with a direction of -1
, it will return with names as "a,b,c,d" as you'd expect. Then I'll sort again (changing the direction to 1
) and it will reverse the direction. But then if I sort it again (with direction === -1
), it will return with an order of "a,c,b,d".
This is a simplified example; in reality it's far less predictable than this.
I have a feeling I'm not using the direction
properly in my sort. See below:
this.sortData = function (data, type, direction) {
return data.sort(sortFunct);
function sortFunct(a, b) {
var numberTypes = ['Thread', 'Job', 'FolderCount', 'MessageCount', 'EmailCount', 'CalendarCount', 'TaskCount', 'OtherCount', 'JobId', 'BatchId', 'ItemsTotal', 'ItemsRemaining', 'ItemsFailed', 'Size', 'progress', 'PercentComplete'];
var stringTypes = ['Level', 'StatusMessage', 'Author', 'ItemStatus', 'JobStatus', 'SourceMailbox', 'TargetMailbox', 'Subject', 'Folder', 'MessageClass', 'StatusMessage', 'Path', 'Owner1',];
if (numberTypes.indexOf(type) !== -1) {
return direction * (a[type] - b[type]);
} else if (stringTypes.indexOf(type) !== -1) {
if (!a[type]) {
return 1;
} else if (!b[type]) {
return -1;
} else {
return a[type].localeCompare(b[type]) * direction;
}
} else if (type === 'DiscoveryDate' || type === 'ReceivedDate' || type === 'Timestamp') {
if (a[type] > b[type]) {
return direction * 1;
} else if (a[type] < b[type]) {
return direction * -1;
} else {
return 0;
}
} else {
return direction * (a[type] - b[type]);
}
} // End sortFunct
};