栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

JavaScript 如何按日期属性对数组排序

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JavaScript 如何按日期属性对数组排序

最简单的答案

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

或更简洁:

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

通用,有力的答案

在所有数组上

sortBy
使用Schwartzian变换定义一个自定义不可枚举的函数:

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

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

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

如果返回值数组,还可以使用它来按多个条件排序:

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/415918.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号