JavaScript: Sort object by a value
Actually the headline is not really what I want to say :-). But I don’t know any better yet.
I just want to write down how I solved sorting the following:
>>> var maxSpeed = {car:300, bike:60, motorbike:200, airplane:1000,
helicopter:400, rocket:8*60*60}
This is a list of vehicles with their (approx.) max speeds. And now, I would like a list of the vehicles sorted by their max speed. This looks sooo easy, and actually it is :-). You just have to know how.
Look at this:
>>> var sortable = [];
>>> for (var vehicle in maxSpeed)
sortable.push([vehicle, maxSpeed[vehicle]])
>>> sortable.sort(function(a, b) {return a[1] - b[1]})
[["bike", 60], ["motorbike", 200], ["car", 300],
["helicopter", 400], ["airplane", 1000], ["rocket", 28800]]
Since the sort function takes an extra argument, that allows to do your custom comparison we simply make sure that the right stuff gets compared, which is our speed. Unfortunately we can not sort the object directly, it has to be an array for doing so. But you can now convert it back, or just extract the vehicles, like so:
>>> dojo.require("dojox.lang.functional")
>>> vehiclesSortedBySpeed =
dojox.lang.functional.map(sortable, function(i) {return i[0]})
["bike", "motorbike", "car", "helicopter", "airplane", "rocket"]
Didn’t I say it was easy?
peter higgins said,
May 20, 2008 at 7:38 pm
function sortObj(theObj, idx){
var sortable = [];
for(var i in theObj){
sortable.push([i, theObj[i]]);
}
sortable.sort(function(a,b){
return a[idx] - b[idx];
});
return dojo.map(sortable,function(elm){ return elm[0]; });
}
var obj = {
car: 300, bike:60, motorbike:200, airplane:1000,
helicopter: 500, rocket: 8*60*60
};
console.log(sortObj(obj,1));
Thomas Frank said,
May 27, 2008 at 12:58 am
I wrote a sorter for arrays of objects a while ago that also comes to mind:
http://www.thomasfrank.se/sorting_things.html
Felipe Delgado said,
October 12, 2010 at 7:29 pm
I tried to make work the array like you have, and I can’t; instead of, I made an array of JSON objects, like this:
var maxSpeed = [
{vehicle:'car', velocity:300},
{vehicle:'bike',velocity:60},
{vehicle:'motorbike',velocity:200},
{vehicle:'airplane', velocity:1000},
{vehicle:'helicopter',velocity:400},
{vehicle:'rocket', velocity:8*60*60}
];
then, I used a sorting function that sort the array using the velocity property of the objects.
function SortByVelocity(a,b)
{ return a.velocity - b.velocity; }
maxSpeed.sort(SortByVelocity);
and it’s works very fine!
Naveen said,
April 4, 2011 at 8:13 am
I am also searching for similar kind of sorting. Kindly give me an idea how do we implement this in a class using a private method.
Nathan Rose said,
May 18, 2012 at 12:35 am
Use Felipe’s solution — works fantastic!
Steve said,
June 6, 2012 at 4:14 pm
+1 for Felipe’s solution…3 lines of magic right there, especially if you already have a json array.
azpbdcwwy said,
December 9, 2012 at 10:52 pm
ugg boots Flat relaxed espadrilles have grown quite well-liked and they are the the latest fad. Having said that, there are several people who even choose carrying heeled sandals. For them, the very best decision might be the wedge espadrille shoes. You may as well validate on the net for the most current Juicy Couture purses. For all your online buys you’ll be able to commit employing PayPal, the important thing credit score cards, or simply by loan company transfers. For being on the risk-free and sound aspect you have got to deal with a accredited retail retail outlet in order that you are able to avoid the hazard of surrendering your very difficult-earned revenue to rogue traders..
louis vuitton outlet Lv Rapid Baggage exhibit up in improved variations like: thirty, Thirty, 27, Lv Straps and 50. The principal accurate acclimated will be the Initialed or monogrammed Product that is changeable and also ethereal and contains now recently been Louis Vuitton’s design all over again 1896. Finding completely watertight capable to tolerate evident scores, it truly is completely ill-fitted towards the genuine louis vuitton wallet grownup and in addition burghal life style..
http://www.bestuggobootsoutlet.com he Monogram Canvas Koala M58013 ply demonstrates awesome Gucci Aviatrix Medium Boston Bag Black winsomeness encouraged by Monogram Canvas Cabas Mezzo Massive M51151 the discriminative patterns Thomas Wylde Oxford Clutch Silver in the seventies. reproduction louis vuitton purses The foremost Chopard reproduction Gucci Purses handbags operate may be reproduction Thomas Wylde Purses purses designed not inform Chanel Paris Biarritz Tote Croc Veins Bag the belief that Suhali Leather-based Le Fabuleux White M91815 velocity up lovers replica Wallet Hermes motive an markedly reproduction purses out-and-out chronograph. The Gucci Handbag Apricot 131186 latest-generation ‘Swiss made’ Gucci PELHAM Medium Shoulder Bag 153691 Brown quartz movements, energetic Monogram Canvas Monogram Good Magnificence Situation M47280 the look at, is Fendi Spring/Summer Espresso Rabbit Hair 2575 chronomet reproduction gucci handbags Chanel Massive Cowskin Tote Black Chanel Wallet White Black C0168 reproduction Coach Handbags purses replica gucci handbags he reproduction knockoffs fake handbags ply demonstrates interesting bogus purses winsomeness inspired by good quality fake-Wallets the discriminative layouts knockoffs purses with the seventies.
uggs australia It may be demanding to finish smoking cigarettes but attempt and work out the harmful effect it’s got not merely on you but in addition with your family members. That you are placing your family’s lifestyle in jeopardy who will not possess the regimen of smoking. Think about seeing anyone younger suffering and also dying in the clinic.
magLaubsabaph said,
January 16, 2013 at 6:53 pm
buy Efavirenz 500 mg
Sustiva 600 mg online
buy Generic Sustiva 600 mg
purchase Generic Sustiva online