11

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
  • 669,327
  • 51
  • 454
  • 560
Titus Sutio Fanpula
  • 3,079
  • 3
  • 13
  • 31

1 Answers1

23

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
  • 31,610
  • 8
  • 53
  • 74
marmeladze
  • 6,048
  • 3
  • 24
  • 42
  • 8
    No need to convert to Date. ISO dates can be compared lexicographically. – Barmar Sep 12 '18 at 03:33
  • 1
    thanks Barmar, I've edited my answer – marmeladze Sep 12 '18 at 03:44
  • 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
  • *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