Solutions Log

So I only have to figure things out once.

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

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

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

1
2
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:

1
2
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

JavaScript

Comments