I have a condition where I'm stuck right now, so basically I want to sort my array with the values of its nested array. I want to sort the parent array called arr with the date-time of its nested array called notifications. I want only those objects should come first which has updated createdAt of notifications.
const arr = [
{
"name": "Two"
"notifications": [
{
"name": "Notification of two (1)",
"createdAt": "2021-03-17T10:30:03.629262Z"
},
{
"name": "Notification of two (1)",
"createdAt": "2021-03-17T10:30:03.629262Z"
}
]
},
{
"name": "One"
"notifications": [
{
"name": "Notification of one (1)",
"createdAt": "2022-03-17T10:30:03.629262Z"
},
{
"name": "Notification of one (1)",
"createdAt": "2022-03-17T10:30:03.629262Z"
}
]
}
]
Here's one way to solve the problem. It calculates the maximum date for each item's notification and then performs a descending sort on that maximum date.
const arr = [
{
name: "Two",
notifications: [
{
name: "Notification of two (1)",
createdAt: "2021-03-17T10:30:03.629262Z",
},
{
name: "Notification of two (1)",
createdAt: "2021-03-17T10:30:03.629262Z",
},
],
},
{
name: "One",
notifications: [
{
name: "Notification of one (1)",
createdAt: "2022-03-17T10:30:03.629262Z",
},
{
name: "Notification of one (1)",
createdAt: "2022-03-17T10:30:03.629262Z",
},
],
},
];
const max_date = (x) =>
Math.max.apply(
null,
x.notifications.map((n) => new Date(n.createdAt))
);
// Descending sort by maximum date
arr.sort((x, y) => max_date(y) - max_date(x));
console.log(arr);
Answer to follow-up question: if instead of createdAt being a timestamp, let's say you had a simple boolean called notified and you wanted to sort notified items before non-notified items.
In the example below we simply count the number of notified=true properties and sort descending on that. So, all items with 1+ notified=true come before items with 0 notified=true and an item with 2x notified=true comes before an item with 1x notified=true.
const notif_count = (x) => x.notifications.filter((n) => n.notified).length;
// Descending sort by count of notified=true
arr.sort((x, y) => notif_count(y) - notif_count(x));