-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.

2
  • Results from Google Commented Sep 1, 2020 at 12:06
  • you have to set the date format to "YYYY-MM-DD" then you can compare directly Commented Sep 1, 2020 at 12:07

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.