[英]Filtered array with the most recent date in javascript
我有一個具有相同隊列 ID、stats_type 和 service_date_end 的數組
[
{
cohort_id: '1',
stats_type: 'comprehensive',
service_date_end: '2020-11-30',
calculation_time: '2021-01-04 11:20:20'
},
{
cohort_id: '1',
stats_type: 'comprehensive',
service_date_end: '2020-11-30',
calculation_time: '2021-01-04 09:20:20'
},
{
cohort_id: '1',
stats_type: 'comprehensive',
service_date_end: '2020-11-30',
calculation_time: '2021-01-04 09:19:20'
},
{
cohort_id: '1',
stats_type: 'comprehensive',
service_date_end: '2020-11-30',
calculation_time: '2021-01-03 09:19:20'
},
{
cohort_id: '1',
stats_type: 'comprehensive',
service_date_end: '2021-01-01',
calculation_time: '2021-01-01 09:19:20'
},
{
cohort_id: '1',
stats_type: 'comprehensive',
service_date_end: '2020-11-30',
calculation_time: '2021-01-01 09:19:20'
},
{
cohort_id: '1',
stats_type: 'diagnostic',
service_date_end: '2020-11-30',
calculation_time: '2021-01-03 09:19:20'
},
{
cohort_id: '1',
stats_type: 'diagnostic',
service_date_end: '2020-11-30',
calculation_time: '2021-01-02 09:19:20'
}
]
對於每個相同的統計數據類型和服務日期結束,我只想擁有那些具有最新計算時間的記錄,並從數組中消除其他數據我如何在 JavaScript 中實現這一點?
您可以使用reduce
和Object.values
過濾它,如下所示:
const data = [{ cohort_id: '1', stats_type: 'comprehensive', service_date_end: '2020-11-30', calculation_time: '2021-01-04 11:20:20' }, { cohort_id: '1', stats_type: 'comprehensive', service_date_end: '2020-11-30', calculation_time: '2021-01-04 09:20:20' }, { cohort_id: '1', stats_type: 'comprehensive', service_date_end: '2020-11-30', calculation_time: '2021-01-04 09:19:20' }, { cohort_id: '1', stats_type: 'comprehensive', service_date_end: '2020-11-30', calculation_time: '2021-01-03 09:19:20' }, { cohort_id: '1', stats_type: 'comprehensive', service_date_end: '2021-01-01', calculation_time: '2021-01-01 09:19:20' }, { cohort_id: '1', stats_type: 'comprehensive', service_date_end: '2020-11-30', calculation_time: '2021-01-01 09:19:20' }, { cohort_id: '1', stats_type: 'diagnostic', service_date_end: '2020-11-30', calculation_time: '2021-01-03 09:19:20' }, { cohort_id: '1', stats_type: 'diagnostic', service_date_end: '2020-11-30', calculation_time: '2021-01-02 09:19:20' } ] const result = Object.values( data.reduce((res, ele) => { let exist = res[ele.stats_type + ele.service_date_end]??= {...ele} if(exist.calculation_time < ele.calculation_time) exist.calculation_time = ele.calculation_time return res }, {}) ) console.log(result)
用??=
文件
邏輯 nullish assignment (x??= y)
運算符僅if x is nullish (null or undefined)
分配。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.