Blog coding and discussion of coding about JavaScript, PHP, CGI, general web building etc.

Monday, June 27, 2016

Sort Javascript Object Array By Date

Sort Javascript Object Array By Date


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?

UPDATE

In my specific case, I wanted the dates arranged from the most recent to the oldest. It ended up that I had to reverse the simple function's logic as so:

array.sort(function(a, b) {      a = new Date(a.dateModified);      b = new Date(b.dateModified);      return a>b ? -1 : a

This sorts the dates from the most recent.

Answer by Phrogz for Sort Javascript Object Array By Date


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

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.

Answer by qw3n for Sort Javascript Object Array By Date


After correcting the JSON this should work.

var array = [{id: 1, date:'Mar 12 2012 10:00:00 AM'},{id: 2, date:'Mar 8 2012 08:00:00 AM'}];      array.sort(function(a,b){  var c = new Date(a.date);  var d = new Date(b.date);  return c-d;  });  

Answer by gabitzish for Sort Javascript Object Array By Date


Your data needs some corrections:

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

After correcting the data, you can use this piece of code:

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

Answer by Gal for Sort Javascript Object Array By Date


@Phrogz answers are both great, but here is a great, more concise answer:

array.sort(function(a,b){return a.getTime() - b.getTime()});  

found here: Sort date in Javascript

Answer by Thesane for Sort Javascript Object Array By Date


you can also use this link. it provides callbacks functions that can be passed to generic sort() function

Answer by jherax for Sort Javascript Object Array By Date


A best implementation of sortBy method by implementing Schwartzian transform can be found here:

href="https://gist.github.com/jherax/ce5d7ba5f7bba519a575e1dfe9cd92c8" rel="nofollow">gist: sortBy.js

For now we are going to try this approach gist: sortBy-old.js.
Let's create a method to sort arrays being able to arrange objects by some property.

Creating the sorting function

var sortBy = (function () {      //cached privated objects    var _toString = Object.prototype.toString,        //the default parser function        _parser = function (x) { return x; },        //gets the item to be sorted        _getItem = function (x) {          return this.parser((x !== null && typeof x === "object" && x[this.prop]) || x);        };      // Creates a method for sorting the Array    // @array: the Array of elements    // @o.prop: property name (if it is an Array of objects)    // @o.desc: determines whether the sort is descending    // @o.parser: function to parse the items to expected type    return function (array, o) {      if (!(array instanceof Array) || !array.length)        return [];      if (_toString.call(o) !== "[object Object]")        o = {};      if (typeof o.parser !== "function")        o.parser = _parser;      o.desc = !!o.desc ? -1 : 1;      return array.sort(function (a, b) {        a = _getItem.call(o, a);        b = _getItem.call(o, b);        return o.desc * (a < b ? -1 : +(a > b));      });    };    }());  

Setting unsorted data

var data = [    {date: "2011-11-14T17:25:45Z", quantity: 2, total: 200, tip: 0,   type: "cash"},    {date: "2011-11-14T16:28:54Z", quantity: 1, total: 300, tip: 200, type: "visa"},    {date: "2011-11-14T16:30:43Z", quantity: 2, total: 90,  tip: 0,   type: "tab"},    {date: "2011-11-14T17:22:59Z", quantity: 2, total: 90,  tip: 0,   type: "tab"},    {date: "2011-11-14T16:53:41Z", quantity: 2, total: 90,  tip: 0,   type: "tab"},    {date: "2011-11-14T16:48:46Z", quantity: 2, total: 90,  tip: 0,   type: "tab"},    {date: "2011-11-31T17:29:52Z", quantity: 1, total: 200, tip: 100, type: "visa"},    {date: "2011-11-01T16:17:54Z", quantity: 2, total: 190, tip: 100, type: "tab"},    {date: "2011-11-14T16:58:03Z", quantity: 2, total: 90,  tip: 0,   type: "tab"},    {date: "2011-11-14T16:20:19Z", quantity: 2, total: 190, tip: 100, type: "tab"},    {date: "2011-11-14T17:07:21Z", quantity: 2, total: 90,  tip: 0,   type: "tab"},    {date: "2011-11-14T16:54:06Z", quantity: 1, total: 100, tip: 0,   type: "cash"}  ];  

Using it

Finally, we arrange the array, by "date" property as string

//sort the object by a property (ascending)  //sorting takes into account uppercase and lowercase  sortBy(data, { prop: "date" });  

If you want to ignore letter case, set the "parser" callback:

//sort the object by a property (descending)  //sorting ignores uppercase and lowercase  sortBy(data, {      prop: "date",      desc: true,      parser: function (item) {          //ignore case sensitive          return item.toUpperCase();      }  });  

If you want to treat the "date" field as Date type:

//sort the object by a property (ascending)  //sorting parses each item to Date type  sortBy(data, {      prop: "date",      parser: function (item) {          return new Date(item);      }  });  

Here you can play with the above example:
http://jsbin.com/kucawudaco/

Answer by Andi for Sort Javascript Object Array By Date


For anyone who is wanting to sort by date (UK format), I used the following:

//Sort by day, then month, then year  for(i=0;i<=2; i++){      dataCourses.sort(function(a, b){            a = a.lastAccessed.split("/");          b = b.lastAccessed.split("/");            return a[i]>b[i] ? -1 : a[i]

Answer by Robert for Sort Javascript Object Array By Date


You could use sortBy in underscore js.

http://underscorejs.org/#sortBy

Sample:

var log = [{date: '2016-01-16T05:23:38+00:00', other: 'sample'},              {date: '2016-01-13T05:23:38+00:00',other: 'sample'},              {date: '2016-01-15T11:23:38+00:00', other: 'sample'}];    console.log(_.sortBy(log, 'date'));  

Answer by Amay Kulkarni for Sort Javascript Object Array By Date


i was able to achieve sorting using below lines:

array.sort(function(a, b) {  if (a.AffiliateDueDate > b.AffiliateDueDate) return 1;  if (a.AffiliateDueDate < b.AffiliateDueDate) return -1;                                     })  

Answer by James111 for Sort Javascript Object Array By Date


I'm going to add this here, as some uses may not be able to workout how to invert this sorting method.

To sort by 'coming up', we can simply do swap a & b, like so:

your_array.sort ( (a, b) => {        return new Date(a.DateTime) - new Date(b.DateTime);  });  

Notice that a is now on the left hand side, and be is on the right, :D!


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

Related Posts:

0 comments:

Post a Comment

Popular Posts

Fun Page

Powered by Blogger.