Numerical array sorting in JavaScript

August 26, 2008, 8:26 pm · Filed under: JavaScript

In these troubled times, it can be hard to know whom to trust. In looking for a numerical sort function, the first two articles I found both recommended the same syntax. Both of them were wrong.

andrew.hedges.name



I am a web developer, living and working in New Zealand. I’m into my family, photography and frisbee sports.

How lucky for those in power that people don’t think.
Adolf Hitler


Meta Me

LinkedIn
Twitter
Facebook
Ma.gnolia
Zooomr


Topics

Apple · Business · Coda · Design · Google · JavaScript · jQuery · Life · Marketing · New Mexico · New Zealand · PHP · Politics · Ruby on Rails · Twitter · Usability · Web Development · Widgets


Archives


Most Popular

Defeat comment spam? Yes we can! · The first 48 hours of PHP Function Reference, by the numbers · There is too much. Let me sum up. · What will be your legacy? · Make long URLs short with tr.im.it · On the value of Twitter · Coda 1.5 is the bee’s knees · Series on hold: What a surprise… · Radiant JavaScript Singletons Freelance Down Under · innerHTML versus the DOM: Can’t we all just get along?


Most Recent

Defeat comment spam? Yes we can! · There is too much. Let me sum up. · What will be your legacy? · Make long URLs short with tr.im.it · On the value of Twitter · Ego-surfing, 2001 style! · Stack Overflow: I’m sold! · V8: neither all that nor a bag of chips · Playing to a browser’s strengths: Simple Templates 1.1 · Introducing jQuery Simple Templates


Recent Reads

Encouraged Commentary · Google Weather API informal documentation · html5.org - HTML revisited · Introduction to WAI ARIA · bookoutlines / Predictably Irrational · The Rise of HTML5 · Five CSS design browser differences I can live with · HTML 5: The Markup Language · Avoiding Silos: “link” as a first-class object · The facade design pattern in JavaScript

See more @ Ma.gnolia


Friends

80/20 · 90 Seven Design · Alyson Hurt · Brian Warren · Daniel Lyons · Daniel Schwartz · David Hedges · Joshua Sallach · Kelly Green · Mark Bixby · Method Arts · Morgan Pyne · Piers Harding · Rob Pongsajapan · Ryan Park · seven-gen · Vaughan Rowsell · Vincent Thomé · Voom Studio


Recommended Books on
Web Development

My bias is for references over “cookbooks.” I want to know all of my options, not just one way to do something. Show me the why as well as the how and I am happy.

JavaScript: The Good Parts · JavaScript: The Definitive Guide · Designing with Web Standards · CSS: The Definitive Guide · Prioritizing Web Usability · The Elements of User Experience · Don't Make Me Think: A Common Sense Approach to Web Usability


Subscribe

Atom · RSS 2.0


I’ve hosted this website with pair Networks since 1997. They rock.

This blog is powered by software I wrote. Want some of that? Hire me.

Now, maybe I shouldn’t be casting stones, considering my last blog post. The truth is, the technique those sites offered will work in most cases, but technically leaves scripts open to errors at the edges.

In JavaScript, you can sort an array just by calling its native sort method. By default, this sorts the contents as strings. That’s all fine and dandy when what you’re sorting are, in fact, strings, but not when you’re sorting numbers (e.g., 10 would come before 9).

The remedy for this is to pass a comparison function to the sort method. The comparison function needs to return -1 if the first argument should come before the second argument, 0 if they are equivalent in sort order, and 1 if the first argument should come after the second.

In most cases, the following syntax (suggested by both of the above linked sites) would work:

var myArray = [10, 9];
myArray.sort(function (a, b) {
   return a - b;
});
// myArray is now [9, 10]

It’s terse. It’s simple. Looks good, right? Wrong.

The Mozilla Developer Center (an authoritative source, I reckon) has this to say about the above technique:

To compare numbers instead of strings, you should not subtract the numbers because this can cause overflow. For example, 9e307-(-9e307) equals Number.POSITIVE_INFINITY but so does 9e307-(-9.9e307).

The solution is to be more explicit in the comparisons. Here’s the syntax I’ve settled on for this:

var myArray = [10, 9];
myArray.sort(function (a, b) {
   return a > b ? 1 : a < b ? -1 : 0;
});
// myArray is now [9, 10]

The moral of the story: check multiple sources, watch for non-obvious gotchas, and never, ever take candy from strangers.

Fin

Comments close automatically after 15 days.
Still have something to say? Drop me a line!