-1

I am having trouble trying to make these datetimes in array sortable. How is this solved?

var array = [{id: 1, date: '16-04-2021 14:24:14'}, {id: 2, date: '16-04-2021 14:24:15'}];


const sortedArray = array.sort(function(a,b){
  
  // Returns = null
  console.warn(new Date(b.date))
  
  return new Date(b.date) - new Date(a.date);
});
Mads Hjorth
  • 439
  • 1
  • 9
  • 23
  • 1
    The `date` in your array is not a format the `Date` constructor recognizes. – Cerbrus Jul 09 '21 at 09:20
  • `new Date(whatever)` never returns *null*, it only ever returns a [*Date* object](https://262.ecma-international.org/#sec-date) (possibly an invalid Date with NaN as the time value) or throws an error. – RobG Jul 14 '21 at 22:46

1 Answers1

-1

You can convert it into valid date format as

const createValidDate = (s) => {
  const strArr = s.split(" ");
  strArr[0] = strArr[0].split("-").reverse().join("-");
  return strArr.join(" ");
};

const createValidDate = (s) => {
  const strArr = s.split(" ");
  strArr[0] = strArr[0].split("-").reverse().join("-");
  return strArr.join(" ");
};

var array = [
  { id: 1, date: "16-04-2021 14:24:14" },
  { id: 2, date: "16-04-2021 14:24:15" },
];

const sortedArray = array
  .map((obj) => ({ ...obj, date: createValidDate(obj.date) }))
  .sort(function (a, b) {
    console.log(new Date(b.date));
    return new Date(b.date) - new Date(a.date);
  });

console.log(sortedArray);
DecPK
  • 24,537
  • 6
  • 26
  • 42
  • It doesn't make sense to parse a string to another string that is then parsed by the built–in parser, you might as well parse it once and pass the values directly to the Date constructor. In this case, the string returned by *createValidDate* will return an invalid Date in at least one current browser as it isn't consistent with any of the formats specified in ECMA-262. – RobG Jul 14 '21 at 22:50
  • Consider `let parseDate = s => {let [D, M, Y, H, m, s] = s.split(/\W/); return new Date(Y, M-1, D, H, m, s)};` where *s* is a timestamp like "16-04-2021 14:24:14". :-) – RobG Jul 14 '21 at 22:52