Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort array by date In JavaScript? [duplicate]

Tags:

javascript

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.

like image 888
Titus Sutio Fanpula Avatar asked Sep 12 '18 03:09

Titus Sutio Fanpula


People also ask

How do you sort an array by date?

To sort an array of objects by date property: Call the sort() method on the array. Subtract the date in the second object from the date in the first. Return the result.

Does sort mutate array JavaScript?

The sort() method returns a reference to the original array, so mutating the returned array will mutate the original array as well.


1 Answers

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.

like image 122
marmeladze Avatar answered Sep 22 '22 21:09

marmeladze