假设我有一个包含几个对象的数组:

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

如何按日期元素排序这个数组,从最接近当前日期和时间的日期下来?请记住,数组可能有许多对象,但为了简单起见,我使用2。

我会使用排序函数和自定义比较器吗?


当前回答

您的数据需要更正:

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

在修正数据之后,你可以使用这段代码:

function sortFunction(a,b){  
    var dateA = new Date(a.date).getTime();
    var dateB = new Date(b.date).getTime();
    return dateA > dateB ? 1 : -1;  
}; 

var array = [{id: 1, date: "Mar 12 2012 10:00:00 AM"},{id: 2, date: "Mar 28 2012 08:00:00 AM"}];
array.sort(sortFunction);​

其他回答

如果像我一样,你有一个日期格式为YYYY[-MM[-DD]]的数组,你想在不太特定的日期之前排序更具体的日期,我想出了这个方便的函数:

function sortByDateSpecificity(a, b) {
  const aLength = a.date.length
  const bLength = b.date.length
  const aDate = a.date + (aLength < 10 ? '-12-31'.slice(-10 + aLength) : '')
  const bDate = b.date + (bLength < 10 ? '-12-31'.slice(-10 + bLength) : '')
  return new Date(aDate) - new Date(bDate)
}

简单的回答

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函数:

(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 name
array.sortBy(function(o){ return [ o.date, -o.score, o.name ] };

详情见http://phrogz.net/JS/Array.prototype.sortBy.js。

我有一个对象数组,其中关键“时间”包含ISO格式的日期

示例- 2021-12-24T11:02:20.370705

arr.sort(function(a,b){return a.time > b.time ? 1 : a.time < b.time ? -1 : 0 });

上面的工作对我来说就像一个魅力!

带日期的字符串在JavaScript中是可比较的(如果它们在语法上相同),例如:

'2020-12-01' < '2020-12-02' == true

这意味着你可以在自定义排序函数中使用这个表达式:

var arr = [{id: 1、日期:“2020-12-01”},{id: 1、日期:“2020-12-15”},{id: 1、日期:' 2020-12-12 '}) 函数sortByDate(a, b) { 如果(a.date < b.date) { 返回1; } If (a.date > b.date) { 返回1; } 返回0; } const sorted = arrr .sort(sortByDate); console.log(排序);

谢谢上面那些精彩的回答。我想了一个有点复杂的答案。只是给那些想比较不同答案的人。

const data = [
    '2-2018', '1-2018',
    '3-2018', '4-2018',
    '1-2019', '2-2019',
    '3-2019', '4-2019',
    '1-2020', '3-2020',
    '4-2020', '1-2021'
]

let eachYearUniqueMonth = data.reduce((acc, elem) => {
    const uniqueDate = Number(elem.match(/(\d+)\-(\d+)/)[1])
    const uniqueYear = Number(elem.match(/(\d+)\-(\d+)/)[2])


    if (acc[uniqueYear] === undefined) {
        acc[uniqueYear] = []        
    } else{    
       if (acc[uniqueYear]  && !acc[uniqueYear].includes(uniqueDate)) {
          acc[uniqueYear].push(uniqueDate)
      }
    }

    return acc;
}, {})


let group = Object.keys(eachYearUniqueMonth).reduce((acc,uniqueYear)=>{
    eachYearUniqueMonth[uniqueYear].forEach(uniqueMonth=>{
    acc.push(`${uniqueYear}-${uniqueMonth}`)
  })
  
  return acc;
},[])

console.log(group);   //["2018-1", "2018-3", "2018-4", "2019-2", "2019-3", "2019-4", "2020-3", "2020-4"]