【发布时间】:2016-03-25 01:48:08
【问题描述】:
我在我的 AngularJS 应用程序中使用数组排序功能。它使用变量direction 来确定是以升序(direction === -1)还是降序(direction === 1)方式对数据进行排序。
出了什么问题:有时当我进行排序时,数组中应该位于相同位置的元素被返回到不同的位置,而数组中没有任何实际变化。
例如,如果我有:
var arr = [
{id: 3, name: 'd'},
{id: 2, name: 'b'},
{id: 1, name: 'a'},
{id: 2, name: 'c'}
];
我按“id”对它进行排序,方向为-1,它将返回名称为“a,b,c,d”的名称,正如您所期望的那样。然后我会再次排序(将方向更改为1),它会反转方向。但是,如果我再次对其进行排序(使用direction === -1),它将以“a,c,b,d”的顺序返回。
这是一个简化的例子;实际上,它远比这更难以预测。
我感觉我没有正确使用direction。见下文:
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
};
【问题讨论】:
标签: javascript arrays sorting