I have the following response from a service:
JavaScript
x
31
31
1
const arrDate = [
2
{
3
"id":1,
4
"birthDate":"2022-06-30T14:38:28.003"
5
},
6
{
7
"id":2,
8
"birthDate":"2022-06-30T14:36:48.50"
9
},
10
{
11
"id":3,
12
"birthDate":"2022-06-30T14:35:40.57"
13
},
14
{
15
"id":4,
16
"birthDate":"2022-06-30T13:09:58.451"
17
},
18
{
19
"id":5,
20
"birthDate":"2022-06-30T14:11:27.647"
21
},
22
{
23
"id":6,
24
"birthDate":"2022-06-30T14:55:41.41"
25
},
26
{
27
"id":7,
28
"birthDate":"2022-02-22T11:55:33.456"
29
}
30
]
31
To sort it by date I do the following:
JavaScript
1
4
1
const sortDate = arrDate.sort(function(a, b) {
2
return new Date(a.birthDate) > new Date(b.birthDate);
3
});
4
But the value of “sortDate” is not correct:
JavaScript
1
31
31
1
[
2
{
3
"birthDate":"2022-06-30T14:38:28.003",
4
"id":1
5
},
6
{
7
"birthDate":"2022-06-30T14:36:48.50",
8
"id":2
9
},
10
{
11
"birthDate":"2022-06-30T14:35:40.57",
12
"id":3
13
},
14
{
15
"birthDate":"2022-06-30T13:09:58.451",
16
"id":4
17
},
18
{
19
"birthDate":"2022-06-30T14:11:27.647",
20
"id":5
21
},
22
{
23
"birthDate":"2022-06-30T14:55:41.41",
24
"id":6
25
},
26
{
27
"id":7,
28
"birthDate":"2022-02-22T11:55:33.456"
29
}
30
]
31
Should be:
JavaScript
1
31
31
1
[
2
{
3
"birthDate":"2022-06-30T14:55:41.41",
4
"id":6
5
},
6
{
7
"birthDate":"2022-06-30T14:38:28.003",
8
"id":1
9
},
10
{
11
"birthDate":"2022-06-30T14:36:48.50",
12
"id":2
13
},
14
{
15
"birthDate":"2022-06-30T14:35:40.57",
16
"id":3
17
},
18
{
19
"birthDate":"2022-06-30T14:11:27.647",
20
"id":5
21
},
22
{
23
"birthDate":"2022-06-30T13:09:58.451",
24
"id":4
25
},
26
{
27
"id":7,
28
"birthDate":"2022-02-22T11:55:33.456"
29
}
30
]
31
How can i solve it?, thanks
Advertisement
Answer
The problem is that the comparison function is supposed to return a positive number for if a should be after b, negative if b should be after a, and zero if they should keep the same order. Your function is returning true and false, JS converts true to 1 and false to zero. That means you are never telling sort to put b after a.
have the function return
JavaScript
1
3
1
return new Date(a.birthDate) > new Date(b.birthDate) ? -1 : 1;
2
// copied from a comment
3