我有一个对象数组,我想按所选键的字母顺序切换顺序。
var locationsOrdered = false;
function dynamicSort(property) {
var sortOrder = 1;
if (locationsOrdered) {
if(property[0] === "-") {
sortOrder = -1;
property = property.substr(1);
}
locationsOrdered = false;
} else {
property = '-' + property;
locationsOrdered = true;
}
return function (a,b) {
var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
return result * sortOrder;
}
}
People.sort(dynamicSort('Surname'))
var People = [
{Name: "Name", Surname: "Surname"},
{Name:"AAA", Surname:"ZZZ"},
{Name: "Name", Surname: "AAA"}
];
正如您将从上面看到的那样,我有一个名为dynamicSort
的函数,它接受一个给定的属性,但我希望它切换值,使其在前面给它-
被激活了。因此,如果您运行dynamicSort('Surname')
,那么该函数应该记住之前使用过的Surname
和-
之前。
Essentialy我想在之前使用过的时候撤销订单。
答案 0 :(得分:0)
我更喜欢在类对象中保存排序状态。我相信有更简单的方法可以做到这一点。但这有效,可能会给你如何做得更好的想法。这是jsfiddle
mysort是dynamicSort的一个实例,它保留了您可能正在排序的每个属性的当前状态。
dynamicSort = (function(){
function dynamicSort() {
this.properties = {};
};
dynamicSort.prototype.sort = function(property){
if (typeof this.properties[property] == "undefined"){
// set the initial state
this.properties[property] = 1;
} else {
// toggle the state
this.properties[property] *= -1;
}
var sortOrder = this.properties[property];
return function (a,b) {
var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
return result * sortOrder;
}
}
return dynamicSort;
})();
var People = [
{Name: "Name", Surname: "Surname"},
{Name:"AAA", Surname:"ZZZ"},
{Name: "Name", Surname: "AAA"}
];
mysort = new dynamicSort();
People.sort(mysort.sort('Surname'))
for (person of People){
console.log(person.Name, person.Surname);
}
People.sort(mysort.sort('Surname'))
for (person of People){
console.log(person.Name, person.Surname);
}
第一次按姓氏排序时,它将按升序输出:
名称AAA
姓名姓氏
AAA ZZZ
第二次按姓氏排序,它将按降序输出:
AAA ZZZ
姓名姓氏
名称AAA