Home > Back-end >  How to group the following array and output them in ejs?
How to group the following array and output them in ejs?

Time:04-02

This is the array:

const emails = [
  { email: 'w@w', createdAt: 2022-03-31T17:07:36.675 00:00 },
  { email: 'a@a', createdAt: 2022-03-31T17:07:36.675 00:00 },
  { email: 'w@b', createdAt: 2022-04-31T17:07:36.675 00:00 },
  { email: 'w@c', createdAt: 2022-04-31T17:07:36.675 00:00 },
  { email: 'w@d', createdAt: 2022-06-31T17:07:36.675 00:00 },
]

I want to format it like this in ejs:

<div class='card'>
  <h3>Unique Date</h3>
  <div class='emails'>
    <p>All the emails of that unique date</p>
  </div>
</div>

How can I do that?

CodePudding user response:

In your back end you will want to use reduce and map to group your existing array to do the following.

// Group emails by date
const groupedEmails = emails.reduce((acc, curr) => {
    const date = curr.createdAt.split('T')[0];
    if (!acc[date]) {
        acc[date] = [];
    }
    acc[date].push(curr);
    return acc;
}, {});

// Loop through grouped emails
const groupedEmailsArray = Object.keys(groupedEmails).map(key => {
    return {
        date: key,
        // Sort emails by email in alphabetical order
        emails: groupedEmails[key].sort((a, b) => {
            if (a.email < b.email) {
                return -1;
            }
            if (a.email > b.email) {
                return 1;
            }
            return 0;
        })
    }
});

You will then want to pass groupedEmailArray to your view and render the view like this

<div class='card'>
  <h3>Unique Date</h3>
  <div class='emails'>
    <p>All the emails of that unique date</p>
    <% for(let group of groupedEmailsArray) { %>
      <p>
        <%= group.date %>
        <% for(let item of group.emails) { %>
            <%= item.email %>
        <% } %>
      </p>

      <% } %>
  </div>
</div>

This should yield the result you are looking for.

  • Related