简体   繁体   中英

sort array of objects by property in object

I have an array of objects like:

[
 {date: "2016-01-07T15:01:51+00:00", text: "Lorem ipsum"}, 
 {date: "2016-22-08T15:04:36+00:00", text: "dolor"},
  // etc.
]

How's the best way to sort these by the date property? I'm already mapping this array to a react component, so any solution that works within the map function I guess would be preferred, but not essential.

I'm trying to use the sort() method at the moment, but can't work how to feed it the date property.

You can have a custom sort function:

 var data = [{ date: "2016-07-01T15:01:51+00:00", text: "Lorem ipsum" }, { date: "2016-02-22T15:04:36+00:00", text: "dolor" }, { date: "2015-08-22T15:04:36+00:00", text: "test" }] var result = data.sort(function(a, b) { var date1 = new Date(a.date); var date2 = new Date(b.date); console.log(date1, date2); return (+date1 - +date2); }); console.log(result) 

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