Posted By

nerdfiles on 03/10/10


Tagged

javascript js sorting


Versions (?)

Sort Objects by Date Property


 / Published in: JavaScript
 

  1. Array.prototype.sortByDate = function(sortOrder) {
  2. var objArray = this; // [Obj, Obj, Obj] where each Obj
  3. // has prop: "sortDate" with val: "YYYY-MM-DD"
  4.  
  5. var sBD = function(a, b) {
  6. var dateStringA = a.sortDate.split("-");
  7. var dateStringB = b.sortDate.split("-");
  8. var dateA = new Date(dateStringA[0], dateStringA[1], dateStringA[2]);
  9. var dateB = new Date(dateStringB[0], dateStringB[1], dateStringB[2]);
  10. return dateA - dateB;
  11. };
  12.  
  13. if (sortOrder == "desc") {
  14. objArray.sort(sBD).reverse();
  15. } else if (sortOrder == "asc") {
  16. objArray.sort(sBD);
  17. } else if (!sortOrder) {
  18. objArray.sort(sBD);
  19. }
  20. }

Report this snippet  

You need to login to post a comment.