Here array containing the name along with the updatedTimeStamp propery. I want to sort the array based on the updatedTimeStamp property.
So I am hereby using date-fns library and I want to use this library only , I can do without this library but that’s my requirement to use this library.
I can able to do sort based on the updatedTimeStamp but its not return the name how can I return the name property along with updatedTimeStamp.
JavaScript
x
29
29
1
import { compareDesc } from "date-fns";
2
3
let arr = [
4
{
5
name:"abc",
6
updatedTimeStamp: "2021-12-06 14:09:00.304464"
7
},
8
{
9
name:"xyz",
10
updatedTimeStamp: "2021-12-14 13:41:58.708262"
11
},
12
{
13
name:"thomas",
14
updatedTimeStamp: "2021-12-06 15:39:09.365793"
15
},
16
{
17
name:"Robin",
18
updatedTimeStamp: "2021-12-14 09:15:42.141081"
19
},
20
{
21
name:"Jobin",
22
updatedTimeStamp: "2021-12-14 12:50:29.723421"
23
},
24
{
25
name:"Tobin",
26
27
}
28
];
29
const objArr = arr.map(i => i.updatedTimeStamp).sort(compareDesc)
Advertisement
Answer
I would do it like this instead. You can pas your own function which returns the comparsefunc instead
JavaScript
1
30
30
1
import {
2
compareDesc
3
} from "date-fns";
4
5
let arr = [{
6
name: "abc",
7
updatedTimeStamp: "2021-12-06 14:09:00.304464"
8
},
9
{
10
name: "xyz",
11
updatedTimeStamp: "2021-12-14 13:41:58.708262"
12
},
13
{
14
name: "thomas",
15
updatedTimeStamp: "2021-12-06 15:39:09.365793"
16
},
17
{
18
name: "Robin",
19
updatedTimeStamp: "2021-12-14 09:15:42.141081"
20
},
21
{
22
name: "Jobin",
23
updatedTimeStamp: "2021-12-14 12:50:29.723421"
24
}
25
];
26
// careful since this modifies the original array
27
arr.sort((a, b) => compareDesc(a.updatedTimeStamp, b.updatedTimeStamp))
28
29
// to not mutate the original you can do this
30
const objArr = [arr].sort((a, b) => compareDesc(a.updatedTimeStamp, b.updatedTimeStamp))