JavaScript disappoints yet again: sorting an array of numbers

July 3, 2012 Mark Rushakoff

We were writing a spec yesterday where we had a method that was returning an array of numbers in no particular order, and we wanted to verify its output. It went something like:

expect(model.foo().sort()).toEqual([1, 2, 3, 10, 25]);

The error message from Jasmine was something like “expected [1, 10, 2, 25, 3] to equal [1, 2, 3, 10, 25]”.

I couldn’t believe it. I wanted to sort an array of numbers, and JavaScript decided it would do me a favor and cast them all to strings first.

The workaround is simple: Mozilla recommends just passing a comparison function to sort:

expect(model.foo().sort(function(a, b) {
    return a-b;
})).toEqual([1, 2, 3, 10, 25]);

When you’re working in JavaScript everyday, you learn to expect the unexpected to some extent, but even this one threw me off.

About the Author

Biography

More Content by Mark Rushakoff
Previous
quick tips
quick tips

The following are things I found very helpful, which you also may find make your day-to-day usage of Git mo...

Next
iOS Roundup: Week of June 25, 2012
iOS Roundup: Week of June 25, 2012

Cool things this week: Cloning a GitHub repository through the HTTPS protocol will always ask for authenti...

Enter curious. Exit smarter.

Learn More