How to Sort an Object in Javascript

Javascript is nice. It has a tiny set of native functions, and allows you to do almost anything you’d like. A quick trick I learned today is how to sort an array of objects rather painlessly. Let’s say you have the following array full of objects:

Array Sample
1
2
3
4
5
6
var friendsArray = [
    { name : 'Alex', age : 26 },
    { name : 'Andrew', age : 23 },
    { name : 'Alice', age : 31 },
    { name : 'Amy', age : 15 }
];

You want to sort these people by their age. Javascript has a native .sort function for arrays, that either lexically or numerically sorts an array… but that won’t quite cut it for our use case. Luckily, this method also accepts a function as a parameter to help you sort. Documentation at Mozilla Developer Center. Suitable code would look something more like this:

Custom Sort Function
1
2
3
4
5
6
7
8
9
10
11
var sortByAge = function (first, second) {
    if (first.age < second.age) {
        return -1;
    }
    if (first.age > second.age) {
        return 1;
    }
    return 0;
}

friendsArray.sort(sortByAge);

So you can literally put in any method of comparing first and second that you want and set the return value to be 1 or -1 and the function will sort it appropriately. You could ping two servers and sort by latency, or request a series of recent tweets from an array of Twitter username and sort by most recently posted… The list goes on, but it’s a pretty powerful function beyond face value.