简体   繁体   中英

Sort an array with objects date property

I have an array with objects that looks like this:

{
 Title: "Title",
 Url: "myUrl",
 publishedDate: "19/01/2021"
  },
  {
   Title: "Title 2",
Url: "myUrl",
publishedDate: "17/12/2020"
  },
  {
  Title: "Title 3",
Url: "myUrl",
publishedDate: "11/03/2021"
  },
  {
Title: "Title 4",
Url: "myUrl",
publishedDate: "11/12/2020"
  }

I have saved them in my state (array).

this.state.data

I want to order the objects based on the property "publishedDate" (and without using the new Date() due to memory efficiency). I try:

console.log(this.state.data.sort(function(a, b) {
  var c = new Date(a.publishedDate);
  var d = new Date(b.publishedDate);
  return c.getTime() - d.getTime();
}))

But the objects are not in order. What is wrong in the code? Playground:

https://www.typescriptlang.org/play?#code/FAYw9gdgzgLgBAQwE5IQTzgXjgb2HOAEwRgQC44BtPOAFQEsYAbAUwoCIHmX2AafAKpImHALZohTPvgAOAVwBGTelAAWLQgBESbOOwCMATgD0ABn3GATKcv72+OAF9+BGgS6sOHlnEvTJYhLC0vJKKupaOhz6AOzG+pZWNqb2BM4Obt5ejKxwAMz+woGSIYrKahraMLoGFqZ5SbapTi64wFl63nAALIUieuIl-KHlEVU1+hYJjSkOjg4AusDzwKCQUGCsAHRMYADmABTIqGhbxKRbG0gwBwBmchAgMPSQR7xwCgCUbQQAbshwEBYOAQFgAdzg4yOWxG4UqOk+AG4HP8kERgaCIVCFDCynDItUkQ4kCwYHIkBBAVs9qSGKIWAdvgBaIjU2n0emM5GOT6fYBAA

If the date format is always the same, you can just create the string in format YYYYMMDD and then compare -

 var data = [{ Title: "Title", Url: "myUrl", publishedDate: "19/01/2021" }, { Title: "Title 2", Url: "myUrl", publishedDate: "17/12/2020" }, { Title: "Title 3", Url: "myUrl", publishedDate: "11/03/2021" }, { Title: "Title 4", Url: "myUrl", publishedDate: "11/12/2020" }] var sortedData = data.sort(function(a, b) { a = a.publishedDate.split('/').reverse().join(''); b = b.publishedDate.split('/').reverse().join(''); return a > b? 1: a < b? -1: 0; }); console.log(sortedData);

The solution here also suggests the same (as well as to use .localeCompare as an alternative)

You can use the Date.UTC method that accepts year, month index, day to create your dates and pass these values by parsing your input dates strings like so:

 this.state = { data: [{ Title: "Title", Url: "myUrl", publishedDate: "19/01/2021" }, { Title: "Title 2", Url: "myUrl", publishedDate: "17/12/2020" }, { Title: "Title 3", Url: "myUrl", publishedDate: "11/03/2021" }, { Title: "Title 4", Url: "myUrl", publishedDate: "11/12/2020" }]}; console.log(this.state.data.sort(function(a, b) { var c = Date.UTC(a.publishedDate.split("/")[2], a.publishedDate.split("/")[1] - 1, a.publishedDate.split("/")[0]); var d = Date.UTC(b.publishedDate.split("/")[2], b.publishedDate.split("/")[1] - 1, b.publishedDate.split("/")[0]); return c - d; }))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM