DEV Community

Discussion on: Understanding sort()

Collapse
 
hi_iam_chris profile image
Kristijan Pajtasev

Nice post.

If you don't mind i would just add for string example, it is worth also handling equal case where in case of equal values you return 0 in order to keep it stable sort.

When we have array of strings it doesn't make much difference, but in case of objects sorted based on some property, let's say name, it is worth keeping same order of equal values.

Collapse
 
felix profile image
Felix Guerin

Hey thanks for reading!

I thought about return 0 in case of equal value but from what I've seen, sort() places equal values next to each other in the sorted array even without it. I figured this could allow me to keep my code even shorter.

Have you seen any case where this could lead to errors?

Collapse
 
hi_iam_chris profile image
Kristijan Pajtasev

Not actually error but only if you care about keeping original order.

For example:
[{fName: "john", lName: "doe"}, {fName: "john", lName: "smith"}]

When stable sort (returning 0 for equal) on name it would always return
[{fName: "john", lName: "doe"}, {fName: "john", lName: "smith"}]

But when unstable (returning 1 when greater, -1 every other time or opposite) once will return above next time might opposite order
[{fName: "john", lName: "smith"}, {fName: "john", lName: "doe"}]

So it more depends on requirements

Thread Thread
 
felix profile image
Felix Guerin

I hadn't thought of that! Indeed, I just tested it several times and it IS unstable if you don't return 0 for equal values. I edited the post to include it.

Thank you so much for this!

Thread Thread
 
hi_iam_chris profile image
Kristijan Pajtasev

NP it is really good post regardless :)