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}];

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?

推荐答案

Simplest Answer

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);
});

More Generic Answer

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

Or more tersely:

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

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;
  }
})();

Use it like so:

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 ] };

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

Javascript相关问答推荐

如何在使用fast-xml-parser构建ML时包括属性值?

我可以使用CSS有效地实现最大宽度=100%和最大高度=100%,而无需父母有明确的/固定的宽度和高度,替代方法吗?

如何用显示网格平滑地将元素从一个地方移动到另一个地方?

如何从Intl.DateTimeFormat中仅获取时区名称?

我正在建立一个基于文本的游戏在react ,我是从JS转换.我怎样才能使变量变呢?

覆盖TypeScrip中的Lit-Element子类的属性类型

为什么我的getAsFile()方法返回空?

回溯替代方式

无法读取未定义的属性(正在读取合并)-react RTK

有没有一种直接的方法可以深度嵌套在一个JavaScript对象中?

将相关数据组合到两个不同的数组中

处理app.param()中的多个参数

如果NetSuite中为空,则限制筛选

在GraphQL解析器中修改上下文值

我不知道如何纠正这一点.

在JavaScript中将Base64转换为JSON

对不同目录中的Angular material 表列进行排序

如何将对象推送到firestore数组?

在Reaction Native中,ScrolltoIndex在结束时不一致地返回到索引0

为什么我的Reaction组件不能使用createBrowserRouter呈现?