-2

I have an array :

    const arr = [
      { name: 'abc', date: '30/03/2014' },
      { name: 'cde', date: '30/03/2015' },
      { name: 'fgh', date: '20/04/2014' },
      { name: 'xyz', date: '17/09/2014' },
    ];

How can I sort this array so that the output would be like this:

    const arr = [
      { name: 'cde', date: '30/03/2015' },
      { name: 'xyz', date: '17/09/2014' },
      { name: 'fgh', date: '20/04/2014' },
      { name: 'abc', date: '30/03/2014' },
    ];

// sort the array with date in latest first.

  • [Results from Google](https://www.google.com/search?q=javascript+sort+by+date+string&rlz=1C5CHFA_enBR711BR711&oq=js+how+to+sortb+by+date+st&aqs=chrome.2.69i57j0l2.5669j0j4&sourceid=chrome&ie=UTF-8) – Ele Sep 01 '20 at 12:06
  • you have to set the date format to "YYYY-MM-DD" then you can compare directly – aRvi Sep 01 '20 at 12:07

1 Answers1

0

Using Array#sort with your own sorting comperator. For this split the dates and build with taht in the right sequence a new Date which can be compared.

    const arr = [
      { name: 'abc', date: '30/03/2014' },
      { name: 'cde', date: '30/03/2015' },
      { name: 'fgh', date: '20/04/2014' },
      { name: 'xyz', date: '17/09/2014' },
    ];
    
    arr.sort((a,b) => {
        let tempA = a.date.split('/');
        let tempB = b.date.split('/');
        return ((new Date(tempB[2],tempB[1],tempB[0])) - (new Date(tempA[2],tempA[1],tempA[0])));
    });
    
    console.log(arr);
Sascha
  • 4,576
  • 3
  • 13
  • 34