Answer the question
In order to leave comments, you need to log in
React/Redux How to properly sort an array of data by submit time?
I have an array of users, each user has an array of messages with the date each message was sent.
The task is to sort the user list component by the time of sending, so that users with new messages move to the top of the list. (The first three messages are hardcoded in time),
users: [
{
id: 1,
image: userPhoto1,
name: 'Frank Gonzalez',
messagesData: [
{
messId: 1,
isOwn: null,
messValue: 'Hi there!',
messDate: localDate(2019, 9, 23, 9, 42)
},
{
messId: 2,
isOwn: null,
messValue: 'how`s it going?',
messDate: localDate(2019, 9, 24, 16, 26)
},
{
messId: 3,
isOwn: null,
messValue: 'can`t wait to see you!',
messDate: localDate(2019, 9, 25, 12, 1)
},
],
},
{
id: 2,
image: userPhoto2,
name: 'Austin Bootman',
messagesData: [
{
messId: 1,
isOwn: null,
messValue: 'asdas!',
messDate: localDate(2017, 2, 26, 17, 11)
},
{
messId: 2,
isOwn: null,
messValue: 'how`wa it gawdoing?',
messDate: localDate(2017, 2, 26, 18, 28)
},
{
messId: 3,
isOwn: null,
messValue: 'diam maecenas ultricies mi eget mauris pharetra et ultrices neque ornare aenean euismod elementum nisi\n' +
'\n!',
messDate: localDate(2017, 2, 26, 18, 50)
},
],
},
{
id: 3,
image: userPhoto3,
name: 'Lois Adams',
messagesData: [
{
messId: 1,
isOwn: null,
messValue: 'lorem*10',
messDate: localDate(2015, 5, 26, 17, 11)
},
{
messId: 2,
isOwn: null,
messValue: 'sdklfjdf lskdjgskdlf kjdh?',
messDate: localDate(2015, 5, 26, 17, 11)
},
{
messId: 3,
isOwn: null,
messValue: 'sdf`t dasf sdf asdf s!',
messDate: localDate(2015, 5, 26, 17, 11)
},
],
},
{
id: 4,
image: userPhoto4,
name: 'Christine Ferguson',
messagesData: [
{
messId: 1,
isOwn: null,
messValue: 'Hasdasdre!',
messDate: localDate(2015, 1, 26, 17, 11)
},
{
messId: 2,
isOwn: null,
messValue: 'haghbbing?',
messDate: localDate(2015, 1, 26, 17, 11)
},
{
messId: 3,
isOwn: null,
messValue: 'cdsgeyou!',
messDate: localDate(2015, 1, 26, 17, 11)
},
],
},
],
};
Answer the question
In order to leave comments, you need to log in
If your localDate() returns some number that can be compared, then you can solve it like this:
ObjName.users.map(item=>item.messagesData.map(date=>[date.messDate, date.messValue])).flat().sort((a, b) => a[0] - b[0]).forEach(elem => {
console.log(elem[1]); // выведутся сообщения по времени
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question