DEV Community

Discussion on: Understanding sort()

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 Author

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