-2

this is my json:

enter image description here

and i want to sort this json by date and time. i write below code but it does not work.

this.newsArray.sort((a, b) =>
          new Date(b.time).getTime() - new Date(a.time).getTime());

newsArray contain 4 items as you can see in picture.

how can i fix this problem ?

Mohandes
  • 271
  • 3
  • 6
  • 17
  • 1
    Your code does not reference the `date` property at all. – TypeIA Nov 17 '18 at 19:36
  • sorting JSON?We usually sort Arrays that have an index – El. Nov 17 '18 at 19:37
  • 2
    Please post your array as text, not as a screenshot. – ggorlen Nov 17 '18 at 19:39
  • 1
    You need to compare the two date values correctly. See the [constructor of Date](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) and properly create a date object out of `item.date` and `item.time`. Then, compare the two objects as described in [this answer](https://stackoverflow.com/a/10124053/3233827). There are also libraries for this case of date comparison (date-fns, moment.js, luxon, etc.) – ssc-hrep3 Nov 17 '18 at 19:40

2 Answers2

4

You're creating the Date object with just the time which results in an invalid date. Use the date and the time to create your date object:

const newsArray = [
  {date: '2018-11-17', time: '18:35:00'},
  {date: '2018-11-17', time: '17:35:00'},
  {date: '2018-11-17', time: '16:20:00'},
  {date: '2018-11-17', time: '20:39:00'},
];

const res = newsArray.sort((a, b) =>
          new Date(b.date + ' ' + b.time).getTime() - new Date(a.date + ' ' + a.time).getTime());
          
console.log(res);
slider
  • 12,810
  • 1
  • 26
  • 42
0

You're trying to construct a date from a string like '12:00:00' which is an invalid date.

Try combining .date and .time to make something Date can interpret:

this.newsArray.sort((a, b) =>
      new Date(b.date + 'T' + b.time).getTime() - new Date(a.date + 'T' + a.time).getTime());
Jim B.
  • 4,512
  • 3
  • 25
  • 53