17

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.

2

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

The comparison function is supposed to return a number, not a boolean. The sign of the number is used to determine the ordering.
I have tried to do it, but the month is sorted. How can the dates in the month be sorted sir.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.