[英]date time sorting with nested objects in javascript
我有一种情况,我现在被卡住了,所以基本上我想用它的嵌套数组的值对我的数组进行排序。 我想用名为notifications
的嵌套数组的日期时间对名为arr
的父数组进行排序。 我只希望那些更新了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"
}
]
}
]
这是解决问题的一种方法。 它计算每个项目通知的最大日期,然后在该最大日期执行降序排序。
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);
后续问题的答案:如果不是createdAt
作为时间戳,假设您有一个简单的 boolean 称为notified
并且您希望在非通知项目之前对通知项目进行排序。
在下面的示例中,我们简单地计算notified=true
属性的数量并对其进行降序排序。 因此,所有具有 1+ notified=true
的项目都出现在具有 0 notified=true
的项目之前,具有 2x notified=true
的项目出现在具有 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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.