Steerpike Steerpike - 2 years ago 125
Javascript Question

Sorting JavaScript Object by property value

If I have a JavaScript object such as:

var list = {"you": 100, "me": 75, "foo": 116, "bar": 15};

is there a way to sort the properties based on value? So that I end up with

list = {"bar": 15, "me": 75, "you": 100, "foo": 116};

I'm having a real brain-dead moment regarding this.

Answer Source

Move them to an array, sort that array, and then use that array for your purposes.

Here's a solution I found via Google:

var maxSpeed = {car:300, bike:60, motorbike:200, airplane:1000,
    helicopter:400, rocket:8*60*60}
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]]

Once you have the array, you could rebuild the object from the array in the order you like, thus achieving exactly what you set out to do. That would work in all the browsers I know of, but it would be dependent on an implementation quirk, and could break at any time. You should never make assumptions about the order of elements in a JavaScript object.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download