JavaScript Sort by Two Fields
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
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.
Written by David Collingwood
Related protips
1 Response
Thanks for sharing this great stuff!
It got me thinking about sorting by even more keys. I came up with the following, which seems to work, for Microsoft Virtual Academy's car lot example with car year, car make, and car model in Lesson 15 on Object Literals at:
I'm a JavaScript newbie, but as far as I can tell, it can be scaled up to as many keys as necessary:
carLot.sort(function(a,b){
return a.year>b.year?true:(a.make>b.make?true:(a.model>b.model?true:false));
});