[FIXED] Filter an array of objects with latest date if array contains same date with different timestamp in multiple objects

Issue

I have an array of objects and each object has the date. I need to filter the array and get the objects that contains latest date.

[
  {
    "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"
  }
         
] 

After filtering the array I need the array should look like below

[
  {
    "Id": 27,
    "MeasureDate": "2022-08-26T16:12:01.001Z"
  },
  {
    "Id": 31,
    "MeasureDate": "2022-08-27T10:20:10.001Z"
  }
]

Solution

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]));
 

Answered By – Dave Pile

Answer Checked By – Willingham (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published