0

I have an array of message objects, like this one:

const messages = [
   {
     id: "messageId",
     text: "Hello!",
     date: new Date("2021/01/01")
   },
   {
     id: "messageId",
     text: "Same day!",
     date: new Date("2021/01/01")
   },
   {
     id: "messageId",
     text: "Another day!",
     date: new Date("2021/01/02")
   },
];

As you can see, every object has a native JS Date. How can I group all those objects in an array, by day, using JavaScript lambdas? This is the expected result:

 [
   {
     day: new Date("2021/01/01"),
     data: [
       {
          id: "messageId",
          text: "Hello!",
       },
       {
          id: "messageId",
          text: "Same day!",
       },
     ]
   },
   {
     day: new Date("2021/01/02"),
     data: [
       {
          id: "messageId",
          text: "Another day!",
       },
     ]
   },
];
Raul
  • 2,673
  • 1
  • 15
  • 52

1 Answers1

2

You could use reduce object to first create object and group by date (year-month-day) and then use Object.values to get an array from that object.

const messages = [
   {
     id: "messageId",
     text: "Hello!",
     date: new Date("2021/01/01")
   },
   {
     id: "messageId",
     text: "Same day!",
     date: new Date("2021/01/01")
   },
   {
     id: "messageId",
     text: "Another day!",
     date: new Date("2021/01/02")
   },
];

const object = messages.reduce((r, { date: day, ...rest }) => {
  const key = `${day.getFullYear()}-${day.getMonth()}-${day.getDate()}`
  if (!r[key]) r[key] = {day, data: [rest]}
  else r[key].data.push(rest)
  return r;
}, {})

const result = Object.values(object)

console.log(result)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176