Answer the question
In order to leave comments, you need to log in
How to display messages sorted by date like in telegrams?
Let's say we have an array of objects
const arr = [
{id:0, text: "text", date: "2021-05-14T16:29:46.000Z"},
{id:1, text: "text 2", date: "2021-05-14T17:29:46.000Z"},
{id:1, text: "text 3", date: "2021-06-14T17:29:46.000Z"},
]
Answer the question
In order to leave comments, you need to log in
const groupArr = {}
arr.map(message => ({...message, date: new Date(message.date)}))
.sort((m1, m2) => m1.date - m2.date)
.forEach(message => {
const date = message.date.toISOString().split('T')[0]
if (!groupArr.hasOwnProperty(date)) {
groupArr[date] = []
}
groupArr[date].push(message)
})
Object.keys(groupArr).forEach(key => console.log(groupArr[key]))
const sortedArr = arr
.map(({date, ...rest}) =>
({...rest, date: new Date(date)}))
.sort(({date: a}, {date: b}) =>
b - a);
console.log(sortedArr)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question