Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript sort object by dd/mm/yyyy property

most of my question was answered in this thread: How Sort Array Date JavaScript dd/mm/yyyy?

but was wondering how to do this if the date is in an object, ie

var info = [
  {
    name : 'a',
    date : '01/05/2017'
  },
  {
    name : 'b',
    date : '23/12/2013'
  },
  {
    name : 'c',
    date : '22/01/2015'
  }
]

no dice with:

 (info.date).sort(function(a, b){
      var aa = a.split('/').reverse().join(),
          bb = b.split('/').reverse().join();
      return aa < bb ? -1 : (aa > bb ? 1 : 0);
  });

thanks!

like image 608
StephD Avatar asked Dec 07 '25 08:12

StephD


1 Answers

since info is an array, apply sort method to info and info.date and inside the comparator function compare date value of each object inside the array. something like this:

var info = [
  {
name : 'a',
date : '01/05/2017'
  },
  {
name : 'b',
date : '23/12/2013'
  },
  {
name : 'c',
date : '22/01/2015'
  }
]

info.sort(function(a, b){
  var aa = a.date.split('/').reverse().join(),
      bb = b.date.split('/').reverse().join();
  return aa < bb ? -1 : (aa > bb ? 1 : 0);
  });
console.log(info);
like image 178
Dij Avatar answered Dec 09 '25 20:12

Dij