Sorting an Array of Objects in Js

There’s 2 ways I know of to sort an array of object according to a property on the object.

The first would be to modify the toString on an object. Given an array of object, you can do:

Object.prototype.toString = function() {
 return this.name;
};
random_objects.sort();

The second way would be to pass in a function sort()

random_objects.sort(function(a, b) {
    if (a.name < b.name) {
        return -1;
    }

    if (a.name == b.name) {
        return 0;
    }

    if (a.name > b.name) {
        return 1;
    }
});

So, wondering what’s fastest, I decided to try out jsperf which is a site that makes it easy to set up perf tests for js.

Turns out the answer to what’s fastest depends on the browser you use. You can run the tests and see the results for yourself.

Using the change toString() method, in Chrome it’s slowest, but in Safari, it’s the fastest.

Naturally, in a real world example, I would use an object of my own, and not muck about with the base Object prototype. But the idea behind changes the toString prototype is you would change it depending on whatever sorting you needed. (ie: by id, time, tags).