I know to sort:
var num = [1, 10, 6]
is
num.sort(function(a,b){
return a - b;
}
What I don't know is how to sort:
var num = [
{"Bob": 1},
{"Tim": 10},
{"Tom": 6},
];
Any ideas??? Thank you!
I know to sort:
var num = [1, 10, 6]
is
num.sort(function(a,b){
return a - b;
}
What I don't know is how to sort:
var num = [
{"Bob": 1},
{"Tim": 10},
{"Tom": 6},
];
Any ideas??? Thank you!
The array of objects you show is already sorted alphabetically by property names, but if you want to sort by the values associated with properties where the property name isn't known it gets a bit more complicated.
Assuming each object will only ever have one property and you want to sort by the value of that property you can do this:
var num = [
{"Bob": 1},
{"Tim": 10},
{"Tom": 6},
];
num.sort(function(a, b) {
var aVal, bVal, k;
for (k in a)
aVal = a[k];
for (k in b)
bVal = b[k];
return aVal - bVal;
});
// num is now [{"Bob":1},{"Tom":6},{"Tim":10}]
You can actually use the array sort method you mentioned above.
Move the object to an array and then sort that array.
var sorted = [];
for (var person in num) {
sorted.push([person, num[person]]);
}
sorted.sort(function(a,b) {
return a[1] - b[1];
});