I have two array friend[] and messages[] and I have already inserted message array values in the friend array according to their friend id. Now, the main array is the friend array which includes some messages like some friends have messages and some have not. But I want to sort friend array based on the message created_Date, and those friend who have not any messages inside their object they remain same. Here is my code:
data.sort((a, b) => (a.lastMessage ? new Date(a.lastMessage.createdAt).getTime() < new Date(b.lastMessage.createdAt).getTime() : '') ? 1 : -1)
Here is my output which is not sorted according to the last message date:
{
"data": [
{
"block": false,
"user": {
"_id": "60ed4a8c1e0812bb34674983",
"profilePic": "",
"firstName": "sachin",
"lastName": ""
},
"friend": {
"_id": "612d11535c77de82c8a68b0d",
"profilePic": "fsjalk;gja./.coj",
"firstName": "Sachin4",
"lastName": "Kumar"
}
},
{
"block": true,
"user": {
"_id": "60ed4a8c1e0812bb34674983",
"profilePic": "",
"firstName": "sachin",
"lastName": ""
},
"friend": {
"_id": "60ed4838ea237d0b40a16491",
"profilePic": "",
"firstName": "sachin",
"lastName": ""
}
},
{
"block": false,
"user": {
"_id": "60ed4a8c1e0812bb34674983",
"profilePic": "",
"firstName": "sachin",
"lastName": ""
},
"friend": {
"_id": "612d108d14521e598838690e",
"profilePic": "",
"firstName": "Sachin3",
"lastName": "Kumar"
},
"lastMessage": {
"message": "This is my sixth chat.",
"createdAt": "2021-09-06T13:47:50.082Z"
}
}
]
}
Concat elements without lastMessage to sorted elements with lastMessage using Array.filter.
Here's a minimal reproducable example
const data = getData();
const sorted = data.filter(d => d.lastMessage)
.sort((a, b) =>
new Date(a.lastMessage.createdAt) -
new Date(b.lastMessage.createdAt))
.concat(data.filter(d => !d.lastMessage));
document.querySelector(`pre`).textContent =
JSON.stringify(sorted, null, 2);
function getData() {
return [
{
"user": {
"_id": "60ed4a8c1e0812bb34674983",
}
},
{
"user": {
"_id": "60ed4a8c1e0812bb34674983",
},
"lastMessage": {
"createdAt": "2021-09-06T13:47:50.082Z"
}
},
{
"user": {
"_id": "60ed4a8c1e0812bb34674983",
},
},
{
"user": {
"_id": "60ed4a9c140e19bb34674983",
},
"lastMessage": {
"createdAt": "2020-04-02T23:11:12.154Z"
}
},
];
}
<pre></pre>