-1

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!

Brad
  • 159,648
  • 54
  • 349
  • 530
user3007294
  • 931
  • 1
  • 14
  • 33
  • The objects have different properties, so they should mean different things. How do you want to compare them, as they have nothing in common? Should one Bob come before or after ten Tims? – Guffa Dec 18 '13 at 21:12
  • This array is an array of different objects. – AbhinavRanjan Dec 18 '13 at 21:13

2 Answers2

2

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}]
nnnnnn
  • 147,572
  • 30
  • 200
  • 241
  • Thanks! I just tried this out and worked perfectly. Thanks again. – user3007294 Dec 18 '13 at 21:21
  • You're welcome. Remember the function I've shown will only work if you have objects with a single property. (Because as soon as you have multiple properties with unknown names there's no way to determine which one to sort on, unless you start making it _really_ complicated by assuming only one property has a numeric value and looking for that property, or something like that.) – nnnnnn Dec 18 '13 at 21:23
1

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];
});
nnnnnn
  • 147,572
  • 30
  • 200
  • 241
tedi
  • 11
  • 1
  • This doesn't work. When you use `a[1] - b[1]` you're trying to subtract two objects like `{"Bob":1} - {"Tom":6}`, which gives `NaN`. – nnnnnn Dec 18 '13 at 21:22