Mike Ross
Mike Ross

Reputation: 2972

How to print date label once in Javascript

I am building a chat application using vueJs and I would like to display date labels just like whats app.

Messages are received in following format on client side

{

    {
        author: 21,
        created_at: "12:09 pm",
        data: "chat message",
        message_group: "today",
        type: "text" 
    },
    {
        author: 22,
        created_at: "11:30 pm",
        data: "chat message 2",
        message_group: "today",
        type: "text"
    },
    {
        author: 22,
        created_at: "11:29 pm",
        data: "chat message 3",
        message_group: "yesterday",
        type: "text"
    }
}

How do I print messages in following format.

Yesterday
    Chat Message 3
Today
    Chat Message 2
    Chat Message     

How can I do it without grouping the array?

Thank you

Upvotes: 1

Views: 261

Answers (1)

lthh89vt
lthh89vt

Reputation: 164

Can't do it in the comment up there so putting it as an answer.

You can have a computed property or getter (vuex) to get the day labels without grouping as below

// Do your sorting first
computed: {
  dayLabels() {
    return a.reduce((acc, message) => {
      if (!acc.includes(message.message_group)) {
          acc.push(message.message_group);  
      }
      return acc;
    }, []);
  }
}

Upvotes: 1

Related Questions