Skip to content

Instantly share code, notes, and snippets.

@trey
Created May 18, 2012 03:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trey/2722894 to your computer and use it in GitHub Desktop.
Save trey/2722894 to your computer and use it in GitHub Desktop.
Sorting JavaScript Arrays in Numerical Order

Sorting JavaScript Arrays in Numerical Order

I do not understand why this is was so difficult to figure out.

You'll need Underscore.js to play along at home.

Start with an array like

var sizes = [4, 1, 10, 8];

If you just use JavaScript's built in .sort() method, you'll end up with

sizes.sort();
// results in [1, 10, 4, 8]

This is because it sorts lexicographically by default. Why? Because it (doesn't) love you.

Here's how to do it using Underscore's sortBy method:

sizes = _.sortBy( sizes, function( val ){ return val; } );
// results in [1, 4, 8, 10]

Why does this work? I'm not sure. Ask your dad.

Source

@trey
Copy link
Author

trey commented May 18, 2012

@Aymkdn
Copy link

Aymkdn commented Nov 13, 2012

You don't need a third party library to do it. Just do :

var sizes = [4, 1, 10, 8];
sizes.sort(function(a,b) { return a>b }); // -> [1, 4, 8, 10]

@Quuxplusone
Copy link

But watch out for NaN!

@dmitriyK1
Copy link

Array.prototype.sort mutates original array, so it could be bad in some situations

Copy link

ghost commented Jun 12, 2018

Try natural sort,
it will fit most of your usages.
https://github.com/eladkarako/sort/blob/594a531034ebf527c8f300b2852024035f1aced0/index.html#L111-L125
it will support both numeric, US-ASCII - even an extended Unicode, correctly (by using localeCompare inside).

a live example: https://sort.eladkarako.com/ (it is a line-based sort&unique)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment