0

enter image description here

here the messages are displaying in a wrong order the sender message of how are you doing? should be at the bottom of the receiver message of hi heelo how to sort the time ? and here is the code , please help me thanks in advance

       { newArr ? newArr.map((m) => {   
            return  <div className={m.type === "sent" ? 'media media-chat media-chat-reverse' : 'media media-chat'}><p>{m.msg}</p>
            <p>{m.date}</p>
          </div>
          }) : null }
sonam
  • 105
  • 8
  • You haven't said what `date` is (number? Date? string?). If it's a number or Date, the `sort` callback should be: `.sort((a, b) => a.date - b.date)` or oldest to newest (`.sort((a, b) => b.date - a.date)` for newest to oldest). If it's a string, [see this question's answers](https://stackoverflow.com/questions/8900732/sort-objects-in-an-array-alphabetically-on-one-property-of-the-array?r=SearchResults&s=1|116.8924) but basically: `.sort((a, b) => a.date.localeCompare(b.date))` for an ascending lexicographic sort (reverse `a` and `b` in the function body for a descending sort). – T.J. Crowder Dec 30 '20 at 10:23

1 Answers1

1
{ newArr ? newArr.sort((a, b) => a.date > b.date ? 1 : -1).map((m) => {   
  return (
    <div className={m.type === "sent" ? 'media media-chat media-chat-reverse' : 'media media-chat'}><p>{m.msg}</p>
      <p>{m.date}</p>
    </div>)
  }) : null }
Prime
  • 2,809
  • 1
  • 7
  • 23
  • This doesn't handle the case where `a.date` and `b.date` are the same correctly. The `sort` callback should be returning `0` in that case, not -1. – T.J. Crowder Dec 30 '20 at 10:18