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.
JavaScript
x
15
15
1
// below is my data to be manipulat
2
[{
3
"is_latest": "",
4
"created_at": "2021-09-21T21:24:05.000Z",
5
"updated_at": "2021-09-21T17:53:29.000Z"
6
}, {
7
"is_latest": "",
8
"created_at": "2021-09-22T21:24:05.000Z",
9
"updated_at": "2021-09-22T17:53:29.000Z"
10
}, {
11
"is_latest": "",
12
"created_at": "2021-09-29T21:24:05.000Z",
13
"updated_at": "2021-09-29T17:53:29.000Z" // this is the latest data
14
}]
15
I’m trying like this, but how to use moment here to compare which is latest.
JavaScript
1
6
1
for (var i = 0; i < data.length; i++) {
2
if (data[i].updated_at > data[i + 1].updated_at) {
3
data.is_latest = "true"
4
}
5
}
6
But I’m not getting the expected result as below.
JavaScript
1
14
14
1
[{
2
"is_latest": "false",
3
"created_at": "2021-09-21T21:24:05.000Z",
4
"updated_at": "2021-09-21T17:53:29.000Z"
5
}, {
6
"is_latest": "false",
7
"created_at": "2021-09-22T21:24:05.000Z",
8
"updated_at": "2021-09-22T17:53:29.000Z"
9
}, {
10
"is_latest": true,
11
"created_at": "2021-09-29T21:24:05.000Z",
12
"updated_at": "2021-09-29T17:53:29.000Z"
13
}]
14
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;
JavaScript
1
33
33
1
var data = [
2
{
3
"is_latest": "",
4
"created_at": "2021-09-21T21:24:05.000Z",
5
"updated_at": "2021-09-21T17:53:29.000Z"
6
},
7
{
8
"is_latest": "",
9
"created_at": "2021-09-22T21:24:05.000Z",
10
"updated_at": "2021-09-22T17:53:29.000Z"
11
},
12
{
13
"is_latest": "",
14
"created_at": "2021-09-29T21:24:05.000Z",
15
"updated_at": "2021-09-29T17:53:29.000Z"
16
},
17
{
18
"is_latest": "",
19
"created_at": "2021-09-30T21:24:05.000Z",
20
"updated_at": "2021-09-30T17:53:29.000Z"
21
}
22
]
23
var maxDateIndex = 0;
24
25
var newData = data.map((item, index) => {
26
if(item.updated_at > data[maxDateIndex].updated_at)
27
maxDateIndex = index;
28
item.is_latest = "false";
29
return item;
30
});
31
32
newData[maxDateIndex].is_latest = "true";
33
console.log(newData);