10

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?

JAbrams
  • 325
  • 4
  • 7
  • 18
  • 1
    what version of loadash you are using? – Nicholas Mar 01 '17 at 19:08
  • 1
    @Nicholas ^4.17.4 – JAbrams Mar 01 '17 at 19:14
  • You need a descending order sort. I don't know what version of Loadash you are using. You can try the options in the accepted answer. [This link.](http://stackoverflow.com/questions/22928841/lodash-multi-column-sortby-descending/29082994#29082994) – Nicholas Mar 01 '17 at 19:11

1 Answers1

22

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();
FuzzyTree
  • 32,014
  • 3
  • 54
  • 85
  • thanks, this was helpful. The issue I'm having now is actually using this inside the render method's return since a "sorted_meetings" would not be defined there. – JAbrams Mar 01 '17 at 19:34
  • 1
    @JessiAbrams if you open a new question I'll take a look – FuzzyTree Mar 01 '17 at 21:13
  • 1
    @JessiAbrams It should be inside the `render() {…var sorted_meetings…return(…something else)}` but not inside of the return `render(){return(…not here…)}` – Elijah Murray Jun 04 '18 at 23:09