16

I have a problem to sort arrays that are in an array object by date.

I have an array object as below.

[
  {
    "name": "February",
    "plantingDate": "2018-02-04T17:00:00.000Z",
  },
  {
    "name": "March",
    "plantingDate": "2018-03-04T17:00:00.000Z",
  },
  {
    "name": "January",
    "plantingDate": "2018-01-17T17:00:00.000Z",
  }
]

How to sort the array in the array object from January to December, as below.

[
  {
    "name": "January",
    "plantingDate": "2018-01-17T17:00:00.000Z",
  },
  {
    "name": "February",
    "plantingDate": "2018-02-04T17:00:00.000Z",
  },
  {
    "name": "March",
    "plantingDate": "2018-03-04T17:00:00.000Z",
  }
]

I beg for help.

Thank you in advance.

Barmar
  • 741,623
  • 53
  • 500
  • 612
Titus Sutio Fanpula
  • 3,467
  • 4
  • 14
  • 33

1 Answers1

31

Parse strings to get Date objects, then sort by compare function.

var a = [
  {
    "name": "February",
    "plantingDate": "2018-02-04T17:00:00.000Z",
  },
  {
    "name": "March",
    "plantingDate": "2018-03-04T17:00:00.000Z",
  },
  {
    "name": "January",
    "plantingDate": "2018-01-17T17:00:00.000Z",
  }
]

a.sort(function(a,b){
  return new Date(a.plantingDate) - new Date(b.plantingDate)
})

console.log(a)

As Barmar commented,

a.sort(function(a,b){
  return a.plantingDate.localeCompare(b.plantingDate);
})

will also work.

adiga
  • 34,372
  • 9
  • 61
  • 83
marmeladze
  • 6,468
  • 3
  • 24
  • 45
  • The comparison function is supposed to return a number, not a boolean. The sign of the number is used to determine the ordering. – Barmar Sep 12 '18 at 03:46
  • I have tried to do it, but the month is sorted. How can the dates in the month be sorted sir. – Titus Sutio Fanpula Sep 12 '18 at 03:59
  • 1
    *localeCompare* is better. a.dateValue - b.dateValue might work okay with JS. It does *not* work with TypeScript - wont' compile because of date type. TypeScript expects numeric values including enum. – Venkey Feb 26 '21 at 13:49