suryanaga
suryanaga

Reputation: 4002

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.

Upvotes: 0

Views: 69

Answers (1)

Rajesh
Rajesh

Reputation: 24915

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)

Upvotes: 3

Related Questions