Skip to content
Advertisement

Compare date and time in array of objects

I’m trying to compare the date and time to manipulate my data. I need to check which is the latest data by checking updated_at key inside object.

Below I have given the scenario.

// below is my data to be manipulat
[{
  "is_latest": "",
  "created_at": "2021-09-21T21:24:05.000Z",
  "updated_at": "2021-09-21T17:53:29.000Z"
}, {
  "is_latest": "",
  "created_at": "2021-09-22T21:24:05.000Z",
  "updated_at": "2021-09-22T17:53:29.000Z"
}, {
  "is_latest": "",
  "created_at": "2021-09-29T21:24:05.000Z",
  "updated_at": "2021-09-29T17:53:29.000Z" // this is the latest data
}]

I’m trying like this, but how to use moment here to compare which is latest.

for (var i = 0; i < data.length; i++) {
  if (data[i].updated_at > data[i + 1].updated_at) {
    data.is_latest = "true"
  }
}

But I’m not getting the expected result as below.

[{
  "is_latest": "false",
  "created_at": "2021-09-21T21:24:05.000Z",
  "updated_at": "2021-09-21T17:53:29.000Z"
}, {
  "is_latest": "false",
  "created_at": "2021-09-22T21:24:05.000Z",
  "updated_at": "2021-09-22T17:53:29.000Z"
}, {
  "is_latest": true,
  "created_at": "2021-09-29T21:24:05.000Z",
  "updated_at": "2021-09-29T17:53:29.000Z"
}]

How can I do this by using map() or reduce()?

Advertisement

Answer

You should check it map and get the max date index. and then set its value to true;

var data = [
{
  "is_latest": "",
  "created_at": "2021-09-21T21:24:05.000Z",
  "updated_at": "2021-09-21T17:53:29.000Z"
},
{
  "is_latest": "",
  "created_at": "2021-09-22T21:24:05.000Z",
  "updated_at": "2021-09-22T17:53:29.000Z"
},
{
  "is_latest": "",
  "created_at": "2021-09-29T21:24:05.000Z",
  "updated_at": "2021-09-29T17:53:29.000Z"
},
{
  "is_latest": "",
  "created_at": "2021-09-30T21:24:05.000Z",
  "updated_at": "2021-09-30T17:53:29.000Z"
}
]
var maxDateIndex = 0;

var newData = data.map((item, index) => {
  if(item.updated_at > data[maxDateIndex].updated_at) 
      maxDateIndex = index;
  item.is_latest = "false";
  return item;
});

newData[maxDateIndex].is_latest = "true";
console.log(newData);
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement