在Javascript中切换数组排序(从上升到下降,反之亦然)

时间:2013-01-24 04:30:07

标签: javascript

我正在按照这样排序我的数组:

array.sort((function(index) {
    return function(a, b){
        return (a[index] === b[index] ? 0 : (a[index] < b[index] ? -1 :1));
    };
})(0));

如您所见,它按升序排序。

我的问题是如何切换排序?例如,如果它已经按升序排列,那么我该如何按降序对其进行排序,反之亦然?

我知道要降序排序我需要修改这样的代码:

array.sort((function(index) {
    return function(a, b) {
        return (a[index] === b[index] ? 0 : (a[index] < b[index] ? 1 :-1));
    };
})(0));

但我不知道如何切换。

4 个答案:

答案 0 :(得分:2)

如果您确定数组已排序,则可以使用简单的循环

来反转顺序
var l = array.length;
for(i=0; i< l / 2; i++) {
   var t = array[i];
   array[i] = array[l - 1 - i];
   array[l - 1 - i] = t;
}

更简单的解决方案是使用reverse函数(BTW,检查this SO Q&A以获得不同的反转算法及其性能)

如果您不知道数组的初始状态,那么我建议将自定义属性与将跟踪排序顺序的数组相关联。例如,

function sortArray(a, isAscending) {
  var currentSort = a["my_sort_order"];
  if (typeof currentSort != 'boolean') {
     // assume it be unsorted, use sort alogorithm
     a.sort(function(a,b) { return isAscending ? a - b : b - a; }); // assuming numerical array, modify as per your needs
  } else if (currentSort != isAscending) {
     // sorted but in different order, reverse the order
     a.reverse(); // or use for loop
  }
  // set the sort order
  a["my_sort_order"] = isAscending ? true : false;
}

答案 1 :(得分:2)

你走在正确的轨道上,你需要第三个闭合来存储切换状态。

function fn(reversed){
    return function(){
        reversed = !reversed;
        return function(a,b){
            return (a==b ? 0 : a < b? -1 : 1) * (reversed ? -1 : 1);
        };
    };
};
// usage
var toggleSort = fn();
array.sort(toggleSort())

jsfiddle:http://jsfiddle.net/8JMuj/1/

答案 2 :(得分:2)

怎么样:

var array = [ 2,4,7,12,1,5 ];

array.toggled_sort = function () {
    var self=this;
    this.asc=!this.asc;
    return this.sort(function (l, r) {
        return l > r ? (self.asc ? 1 : -1) : l < r ? (self.asc ? -1 : 1) : 0;
    });
};

array.toggled_sort(); // ==> [ 1,2,4,5,7,12 ]
array.toggled_sort(); // ==> [ 12,7,5,4,2,1 ]
array.toggled_sort(); // ==> [ 1,2,4,5,7,12 ]
array.toggled_sort(); // ==> [ 12,7,5,4,2,1 ]
// etc.

答案 3 :(得分:0)

//Array sort by its object property can be implemented as this where sortType variable is used as the toggle parameter

//sortElement is the object property can be used as variable if you  need to select the property that which is used for sorting

//按日期属性排序var elem1Var = new Date(elem1[sortElement]);

//按字符串属性排序var elem1Var =elem1[sortElement].toUpperCase();

var sortMethod = -1;
if(self.sortType == 'ASC'){
  sortMethod = 1;
}

dataArr.sort(function(elem1,elem2){
  var elem1Var = elem1[sortElement];
  var elem2Var = elem2[sortElement];

  if(elem1Var  < elem2Var){
       return -1*sortMethod;
  }

  if(elem1Var > elem2Var){
       return  1*sortMethod;
  }
  return 0;
 });