-2

How do I sort below array of dates in ascending as well as descending order? For example, I have:

var value = [
        {"ID":"3","date":null},
        {"ID":"24","date":"07/28/2017"},
        {"ID":"65","date":"05/14/2018"},
        {"ID":"36","date":"06/11/2017"},
        {"ID":"27","date":null},
        {"ID":"18","date":"02/26/2018"},
        {"ID":"37","date":null},
        {"ID":"39","date":"05/15/2017"},
        {"ID":"10","date":"06/11/2017"},
        {"ID":"4","date":null},
        {"ID":"8","date":null},
        {"ID":"12","date":"05/15/2017"},
        {"ID":"14","date":"07/28/2017"},
        {"ID":"19","date":"06/11/2017"}
        ];

I'd like the resultant array to look like:

var result = [
        {"ID":"3","date":null},
        {"ID":"27","date":null},
        {"ID":"4","date":null},
        {"ID":"8","date":null},
        {"ID":"39","date":"05/15/2017"},
        {"ID":"12","date":"05/15/2017"},
        {"ID":"36","date":"06/11/2017"},
        {"ID":"10","date":"06/11/2017"},
        {"ID":"19","date":"06/11/2017"}
        {"ID":"24","date":"07/28/2017"},
        {"ID":"14","date":"07/28/2017"},
        {"ID":"18","date":"02/26/2018"},
        {"ID":"65","date":"05/14/2018"}
        ];
Javascript sorting function :

function sortArray(desc, value) {
  if (desc) {
    value.sort(function(a: any, b: any) {
      let aValue = (a["date"]) ? Number(new Date(a["date"])) : Number(new Date(0));
      let bValue = (b["date"]) ? Number(new Date(b["date"])) : Number(new Date(0));
      return bValue - aValue;
    });
  } else {
    value.sort(function(a: any, b: any) {
      let aValue = (a["date"]) ? Number(new Date(a["date"])) : Number(new Date(0));
      let bValue = (b["date"]) ? Number(new Date(b["date"])) : Number(new Date(0));
      return aValue - bValue;
    });
  }
}

I have mention input array as well as expected array.Thanks in advance.

Swapnil Yeole
  • 352
  • 2
  • 7
  • 21

1 Answers1

3

You can use ES6 syntax, and play with .reverse() to get ASC or DESC

value.sort((a, b) => new Date(b.date) - new Date(a.date)).reverse()

Demo - https://jsfiddle.net/zkcsdv01/

or look here for more extended answer Sort Javascript Object Array By Date

ArtemSky
  • 1,043
  • 10
  • 19
  • @SwapnilYeole It is – ArtemSky Dec 13 '17 at 11:21
  • Thanks - this is excellent because the normal ES6 fat arrow function does not work on dates without the `... new Date(b.date) - new Date(a.date) ...` I was trying to do it with just `... b.date - a.date ...` – Aaron Taddiken Aug 22 '18 at 16:31