S
S
sd20562021-06-13 14:38:14
JavaScript
sd2056, 2021-06-13 14:38:14

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"},
]


The output is

"May 15"

text
text 1

"yesterday"

text
text 2

"today"

text
text 3

Answer the question

In order to leave comments, you need to log in

3 answer(s)
C
chincharovpc, 2021-06-13
@sd2056

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]))

D
Dmitry Belyaev, 2021-06-13
@bingo347

const sortedArr = arr
    .map(({date, ...rest}) =>
        ({...rest, date: new Date(date)}))
    .sort(({date: a}, {date: b}) =>
        b - a);
console.log(sortedArr)

A
Alexey, 2021-06-13
@AleksRap

Sort array before output. If the array flies from the back, then send the sorting parameters to the back, sort there and return the desired option

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question