如果数组在多个对象中包含具有不同时间戳的相同日期,则筛选具有最新日期的对象数组



我有一个对象数组,每个对象都有日期。我需要过滤数组并获取包含最新日期的对象。

[
{
"Id": 25,
"MeasureDate": "2022-08-26T00:01:01.001Z"
},
{
"Id": 26,
"MeasureDate": "2022-08-26T11:10:01.001Z"
},
{
"Id": 27,
"MeasureDate": "2022-08-26T16:12:01.001Z"
},
{
"Id": 30,
"MeasureDate": "2022-08-27T00:08:01.001Z"
},
{
"Id": 31,
"MeasureDate": "2022-08-27T10:20:10.001Z"
}

] 

过滤数组后,我需要的数组应该像下面的样子

[
{
"Id": 27,
"MeasureDate": "2022-08-26T16:12:01.001Z"
},
{
"Id": 31,
"MeasureDate": "2022-08-27T10:20:10.001Z"
}
]
const dateItems = [
{
"Id": 25,
"MeasureDate": "2022-08-26T00:01:01.001Z"
},
{
"Id": 26,
"MeasureDate": "2022-08-26T11:10:01.001Z"
},
{
"Id": 27,
"MeasureDate": "2022-08-26T16:12:01.001Z"
},
{
"Id": 30,
"MeasureDate": "2022-08-27T00:08:01.001Z"
},
{
"Id": 31,
"MeasureDate": "2022-08-27T10:20:10.001Z"
}

];
// As we loop through your dateItems array we need to keep track of the Latest DateTime for each day
// Probably the easiest way is to create a key on a property for each date and then attach the object
// from your array to that key if it is the first for that date or later than an existing one.
const latestDateTimesByDate = {};
dateItems.forEach( di => {
// Use the date part of the date time as a key/ property name on the latestDateTimesByDate object
let dateKey = di.MeasureDate.substring(0, 10);

// If that date key doesnt exist or the current MeasureDate  is gretaer than the recorded one
if( !latestDateTimesByDate[dateKey] || di.MeasureDate > latestDateTimesByDate[dateKey].MeasureDate) {
latestDateTimesByDate[dateKey] = di;
}
});
// if you need it as an array then add each of the date properties to an element of an array
const finalArray = [];
Object.keys(latestDateTimesByDate).forEach( key => finalArray.push(latestDateTimesByDate[key]));

以下是您的问题的解决方案:

function similarDates(obj){ 
date_obj = new Date(obj.MeasureDate);
// Getting only the dates with same year, month, day
let sim_dates = popo.filter((objs) => {
date =  new Date(objs.MeasureDate)
return date.toDateString() === date_obj.toDateString()
});
// Returning the similare dates
return sim_dates
}
function filterData(array) {
result = []
while(array.length) {
console.log(array)
var sameElement =  similarDates(array[0]);
// removing all the treated elements from the array
array = array.filter( ( el ) => !sameElement.includes(el));

result.push(sameElement.sort((a, b) => new Date(b.MeasureDate) - new Date(a.MeasureDate)).shift());
}
return result;
}

最新更新