This was a small issue I came across recently and the solution I found was so brilliant I thought it was worth sharing on here.

So the problem was that I had an array like this:

 

var obj = [
    {
        "one": 1,
        "two": 9
    }, {
        "one": 3,
        "two": 5
    }, {
        "one": 1,
        "two": 2
    }
];

 

 

and I wanted to sort it by "one" and then by "two" to get a result like this:

var obj = [
    {
        "one": 1,
        "two": 2,
    }, {
        "one": 1,
        "two": 9
    }, {
        "one": 3,
        "two": 5
    }
];

 

sounds simple enough right? I thought so too, but the sorting algorithm that the browser is using limits your options when it comes to sorting by multiple fields. After a bit of researching I stumbled upon this wonderful solution: http://stackoverflow.com/questions/13211709/javascript-sort-array-by-multiple-number-fields

 

JavaScript sort array by multiple (number) fields

How can I implement a ORDER BY sort1 DESC, sort2 DESC logic in an JSON array like such: var items = '[ { "sort1": 1, "sort2": 3, "name" : "a", ...

stackoverflow.com

obj.sort(function(a, b) {
    return a["one"] - b["one"] || a["two"] - b["two"];
});

This will sort your array by "one" and if they are the same (ie. 0) then it will sort by "two". It's simple, concise, readable, and best of all - works perfectly.

+ Recent posts