簡體   English   中英

JavaScript切換對象數組的順序

[英]JavaScript toggling the order of object array

我有一個對象數組,我想按所選鍵的字母順序來切換順序。

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前加上-

本質上,我想顛倒順序,如果以前使用過的話。

jsFiddle

我更喜歡將排序狀態保存在類對象中。 我相信有更簡單的方法可以做到這一點。 但這有效,並且可以為您提供更好的方法。 這是一個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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM