Shamoon
Shamoon

Reputation: 43491

How can I sort an object in JavaScript based on value?

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);

Upvotes: 0

Views: 116

Answers (3)

RobG
RobG

Reputation: 147343

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.

Upvotes: 0

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340708

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)});

Upvotes: 3

Joe
Joe

Reputation: 82554

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

Upvotes: 0

Related Questions