I get two different resulting sort orders after sorting my array twice using the native sort method in javascript. I’m sorting by the field ‘date’ and ‘createdAt’. I would expect to get the same order of descending results each time I pass the same array to the algorithm but I get a different resulting order each time. Why is that? Example below.
const arr = [
{"id": 0,
"date": new Date("2023-06-02T00:00:00.000Z"),
"createdAt": new Date("2023-06-05T01:48:37.586Z")
},
{
"id": 1,
"date": new Date("2023-06-03T00:00:00.000Z"),
"createdAt": new Date("2023-06-04T01:31:35.901Z"),
},
{
"id": 2,
"date": new Date("2023-06-03T00:00:00.000Z"),
"createdAt": new Date("2023-06-04T17:19:14.733Z"),
},
{
"id": 3,
"date": new Date("2023-06-03T00:00:00.000Z"),
"createdAt": new Date("2023-06-04T21:10:26.454Z"),
},
{
"id": 4,
"date": new Date("2023-06-03T00:00:00.000Z"),
"createdAt": new Date("2023-06-04T21:11:53.192Z"),
},
{
"id": 5,
"date": new Date("2023-06-03T00:00:00.000Z"),
"createdAt": new Date("2023-06-04T21:13:13.879Z"),
},
{
"id": 6,
"date": new Date("2023-06-03T00:00:00.000Z"),
"createdAt": new Date("2023-06-04T21:15:46.841Z"),
},
{
"id": 7,
"date": new Date("2023-06-03T00:00:00.000Z"),
"createdAt": new Date("2023-06-04T21:16:45.006Z"),
},
{
"id": 8,
"date": new Date("2023-06-04T00:00:00.000Z"),
"createdAt": new Date("2023-06-04T17:21:19.906Z"),
},
{
"id": 9,
"date": new Date("2023-06-04T00:00:00.000Z"),
"createdAt": new Date("2023-06-04T21:01:39.286Z"),
},
{
"id": 10,
"date": new Date("2023-06-04T00:00:00.000Z"),
"createdAt": new Date("2023-06-04T21:09:48.776Z"),
},
{
"id": 11,
"date": new Date("2023-06-04T00:00:00.000Z"),
"createdAt": new Date("2023-06-04T21:27:45.701Z"),
}
]
function sortItems(items) {
return items.toSorted((a, b) => {
// do comparison
if (a.date > b.date) {
return -1
} else if (a < b.date) {
return 1
} else {
if (a.createdAt > b.createdAt) {
return -1
} else if (b.createdAt < b.createdAt) {
return 1
} else {
return 0
}
}
})
}
const sort_1 = sortItems(arr)
console.log(sort_1)
const sort_2 = sortItems(sort_1)
console.log(sort_2)
The result is two diffent resulting sort orders. Why is that?
2
Answers
You could simplify your code considerably. And make it more reliable and easier to read:
The expression after the "or" (
||
) will only come into action if the result of the first part is not equal to0
.Please note:
Assigning the
arr.sort(byDates)
results to a new variable, or in this case: a new constant, makes very little sense asArray.prototype.sort()
works "in place". This means that the source array will be changed and only a reference to that same (but re-ordered) array will be returned.If you want to preserve the original sort order in
arr
you shouldArray.prototype.slice()
the array before.sort()
ing it: