DEV Community

Discussion on: Understanding sort()

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 :)