オブジェクト配列を日付プロパティで並べ替えるにはどうすればいいですか? 質問する

オブジェクト配列を日付プロパティで並べ替えるにはどうすればいいですか? 質問する

いくつかのオブジェクトの配列があるとします。

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

この配列を、現在の日付と時刻に最も近い日付から順に日付要素で並べ替えるにはどうすればよいでしょうか。配列には多数のオブジェクトが含まれる可能性がありますが、簡単にするために 2 つ使用しました。

ソート関数とカスタムコンパレータを使用するのでしょうか?

ベストアンサー1

最も簡単な答え

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

一般的で強力な答え

列挙不可能なカスタム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詳細については。

おすすめ記事