0

My object is:

[ '4e95b308d36f429729000021': 1,
  '4e95b309d36f429729000039': 2,
  '4e95b308d36f429729000001': 1 ]

I want to sort so that the 2 valued key is first. I know this question has been asked a million times before, but this doesn't work:

var descSort;
descSort = function(a, b) {
  return b.value - a.value;
};
popularLocationsArray.sort(descSort);
Shamoon
  • 41,293
  • 91
  • 306
  • 570
  • 3
    Your code for the object isn't valid JavaScript. If that's supposed to be an object/dict/map, you need to use `{...}` instead of `[...]`. – Jeremy Oct 12 '11 at 21:07
  • Do you have a typo? [] are used for arrays. {} are used for an object. In addition sort only works with arrays not objects. – styrr Oct 12 '11 at 21:07
  • Is this helpful at all for you? http://stackoverflow.com/questions/1069666/sorting-javascript-by-property-value – Senica Gonzalez Oct 12 '11 at 21:07

3 Answers3

3

First of all your code is not a valid JavaScript, it should be:

var popularLocationsArray = [ 
  {'4e95b308d36f429729000021': 1},
  {'4e95b309d36f429729000039': 2},
  {'4e95b308d36f429729000001': 1} 
]

Knowing that your problem is that you don't know the key name in each object and you want to sort by this key's value. First you need to define a helper function:

function anyVal(obj) {
  for(var key in obj) {
    if(obj.hasOwnProperty(key)) {
      return obj[key]
    }
  }
}

Now sorting is simple:

popularLocationsArray.sort(function(a,b) {return anyVal(a) - anyVal(b)});
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
0

You can't sort an object. An object has no reason to return it's key in any particular order.

Now if you meant something like this, you have options:

function descSort(a, b) {
   var value1 = +a[Object.keys(a)[0]],
       value2 = +b[Object.keys(b)[0]];
   return value2 - value1;
}

[ {'4e95b308d36f429729000021': 1},
  {'4e95b309d36f429729000039': 2},
  {'4e95b308d36f429729000001': 1} ].sort(descSort)

This uses Object.keys, which doesn't have native

Joe
  • 80,724
  • 18
  • 127
  • 145
0

Just to make life interesting, you can make the objects in the array sortable (that is, within a containing array) by creating your own custom object:

function Foo(key, value) {
  this[key] = value;
}
Foo.prototype.toString = function() {
  for (var p in this) {
    if (this.hasOwnProperty(p)) {
      return this[p];
    }
  }
}
var a = new Foo('4e95b308d36f429729000021', 1);
var b = new Foo('4e95b309d36f429729000039', 2);
var c = new Foo('4e95b308d36f429729000001', 1);
var popularLocationsArray = [a, b, c];

alert(popularLocationsArray); // 1, 2, 1

alert(popularLocationsArray.sort()); //1, 1, 2

Or you could make it sort on the key name, or combine the key and property, whatever. Just have the toString method return whatever you want them sorted on.

RobG
  • 142,382
  • 31
  • 172
  • 209