Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React sorting by date

I have a react component that renders list of "Meetings" that have occurred in the past.

I'm trying to get it to sort each past meeting so that those that occurred more recently in the past will be at the top.

I am checking to see if the meeting occurred in the past, if so, display it. (This is working fine)

This is my render method:

render(){
let past_meetings = this.store.meetings.map((meeting, i) => {
  if (meeting.scheduled_for < moment.utc( new Date() ).format()){
    return (<MeetingItem meeting={meeting} key={`meeting-${meeting.id}`} />)
  } else {
    return ;
  }
})

return(
  <div className="">
    <div className=""> 
      <h3 className="">Past Meetings</h3>
      <div className="" > 
        {past_meetings}
      </div>
    </div> 

  </div>
  )
 }

Currently the meetings are shown as: if it happened further in the past, show at the top.

My goal is to get it to show as follows: if it happened more recently, show at the top.

Tried something like this with lodash's .sortBy():

let sorted_meetings = _.sortBy(past_meetings, function(e){
return - (new Date(e.scheduled_for))
}

no success.

meeting.scheduled_for
// returns 2017-03-03T03:33:00.000Z

tried to compare the scheduled_for's but not much luck either.

can this be done with _ ??? or any other way?

like image 511
JAbrams Avatar asked Mar 01 '17 19:03

JAbrams


1 Answers

You can use sort() and reverse() to sort meetings in descending order

var sorted_meetings = meetings.sort((a,b) => {
    return new Date(a.scheduled_for).getTime() - 
        new Date(b.scheduled_for).getTime()
}).reverse();
like image 183
FuzzyTree Avatar answered Oct 18 '22 18:10

FuzzyTree