如何按日期属性对对象数组进行排序? [英] How to sort an object array by date property?

查看:75
本文介绍了如何按日期属性对对象数组进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一些对象的数组:

Say I have an array of a few objects:

var array = [{id: 1, date: Mar 12 2012 10:00:00 AM}, {id: 2, date: Mar 8 2012 08:00:00 AM}];

如何从最接近当前日期和时间的日期开始按date元素对该数组进行排序?请记住,数组可能有许多对象,但是为了简单起见,我使用了2.

How can I sort this array by the date element in order from the date closest to the current date and time down? Keep in mind that the array may have many objects, but for the sake of simplicity I used 2.

我会使用排序功能和自定义比较器吗?

Would I use the sort function and a custom comparator?

推荐答案

最简单的答案

array.sort(function(a,b){
  // Turn your strings into dates, and then subtract them
  // to get a value that is either negative, positive, or zero.
  return new Date(b.date) - new Date(a.date);
});

更多通用答案

array.sort(function(o1,o2){
  if (sort_o1_before_o2)    return -1;
  else if(sort_o1_after_o2) return  1;
  else                      return  0;
});

或更简洁:

array.sort(function(o1,o2){
  return sort_o1_before_o2 ? -1 : sort_o1_after_o2 ? 1 : 0;
});

通用,有力的答案

在所有数组上使用 Schwartzian变换定义自定义不可枚举的sortBy函数:

Generic, Powerful Answer

Define a custom non-enumerable sortBy function using a Schwartzian transform on all arrays :

(function(){
  if (typeof Object.defineProperty === 'function'){
    try{Object.defineProperty(Array.prototype,'sortBy',{value:sb}); }catch(e){}
  }
  if (!Array.prototype.sortBy) Array.prototype.sortBy = sb;

  function sb(f){
    for (var i=this.length;i;){
      var o = this[--i];
      this[i] = [].concat(f.call(o,o,i),o);
    }
    this.sort(function(a,b){
      for (var i=0,len=a.length;i<len;++i){
        if (a[i]!=b[i]) return a[i]<b[i]?-1:1;
      }
      return 0;
    });
    for (var i=this.length;i;){
      this[--i]=this[i][this[i].length-1];
    }
    return this;
  }
})();

像这样使用它:

array.sortBy(function(o){ return o.date });

如果您的日期不可直接比较,请在日期中加上一个可比较的日期,例如

If your date is not directly comparable, make a comparable date out of it, e.g.

array.sortBy(function(o){ return new Date( o.date ) });

如果您返回一个值数组,也可以使用它来按多个条件进行排序:

You can also use this to sort by multiple criteria if you return an array of values:

// Sort by date, then score (reversed), then name
array.sortBy(function(o){ return [ o.date, -o.score, o.name ] };

请参见 http://phrogz.net/JS/Array.prototype.sortBy.js有关更多详细信息.

See http://phrogz.net/JS/Array.prototype.sortBy.js for more details.

这篇关于如何按日期属性对对象数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆