Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (7k points)

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 using the date element in order from the date closest to the current date and time down?

1 Answer

0 votes
by (13.1k points)
edited by

This is the 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);

});

This is the generic, powerful answer:

You can define a custom non-enumerable sortBy function using 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 this:

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

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

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:

array.sortBy(function(o){ return [ o.date, -o.score, o.name ] };

Want to be a Full Stack developer? Check out the Full Stack developer course from Intellipaat.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...