I have seen this, but it does not solve my problem:
How do I group items in an array by date?
I want to arrange this chat message by date, I have successfully retrieved the message from the database using AJAX.
Here is the retrieved chat in the console.
[
[
"Paul Abioro",
"[email protected]",
"chester",
"Teejay",
"Hi Teejay",
"3",
"2023-04-06 17:42:54"
],
[
"Paul Abioro",
"[email protected]",
"chester",
"Teejay",
"How are you doing?",
"3",
"2023-04-06 17:42:58"
],
[
"Teejay Bello",
"[email protected]",
"Teejay",
"chester",
"I'm Fine",
"2",
"2023-04-06 19:00:42"
],
[
"Paul Abioro",
"[email protected]",
"chester",
"Teejay",
"Testing",
"3",
"2023-04-08 10:12:38"
],
[
"Teejay Bello",
"[email protected]",
"Teejay",
"Chester",
"Testing what?",
"2",
"2023-04-08 10:21:09"
],
[
"Paul Abioro",
"[email protected]",
"chester",
"Teejay",
"How can we help you?",
"3",
"2023-04-08 10:38:25"
]
]
What I want to do
[
date": "2023-04-06",
chat":[
"Paul Abioro",
"[email protected]",
"chester",
"Teejay",
"Hi Teejay",
"3",
"2023-04-06 17:42:54"
],
[
"Paul Abioro",
"[email protected]",
"chester",
"Teejay",
"How are you doing?",
"3",
"2023-04-06 17:42:58"
],
[
"Teejay Bello",
"[email protected]",
"Teejay",
"chester",
"I'm Fine",
"2",
"2023-04-06 19:00:42"
],
date": "2023-04-08",
chat":[
"Paul Abioro",
"[email protected]",
"chester",
"Teejay",
"Testing",
"3",
"2023-04-08 10:12:38"
],
[
"Teejay Bello",
"[email protected]",
"Teejay",
"Chester",
"Testing what?",
"2",
"2023-04-08 10:21:09"
],
[
"Paul Abioro",
"[email protected]",
"chester",
"Teejay",
"How can we help you?",
"3",
"2023-04-08 10:38:25"
]
]
I hope you get the idea. Thanks!
2
Answers
you can use array
reduce
to group into an object and then take the values array of the reduced object usingObject.values
.If you want the object grouped by date instead of the array remove the
Object.values
the date portion can be obtained using
curr[curr.length-1].split(" ")[0]
or
curr.at(-1).split(" ")[0]
if your environment supports
at
You can use
reduce
to get the result: