Sharan Mohandas
Sharan Mohandas

Reputation: 871

Sort an Object by Value

I have a JS Object which contains a list of chats. What i need is to sort them in desc order according to the last_message_at value which is an epoch (Unix).

The structre of the Object is as below

var test = {
    "138545616542461": {
        "otherUser": {
            "$id": "128636544201178",
            "$priority": null,
            "age": 35
        },
        "last_message_at": 1268482500
    },
    "138545616542460": {
        "otherUser": {
            "$id": "128636544201178",
            "$priority": null,
            "age": 35
        },
        "last_message_at": 1368482500
    }
};

Typically, the sorted object should have 1368482500 at the Top. Array can be used for sorting purposes but finally the result should be an Object.

Tried some stackoverflow examples with no luck..

Upvotes: 1

Views: 102

Answers (2)

zetavolt
zetavolt

Reputation: 3217

There are a number of important issues prohibiting the exact steps you are trying to accomplish so I've taken the liberty of a quick method that does what I think you want -- namely enumerating the keys of the object and sorting by the numeric value of last_message_at

Object.keys(test)
      .sort((a,b) => {
             return test[a].otherUser.last_message_at - test[b].otherUser.last_message_at; })
      .map((elt) => { return test[elt]; });

This function returns an array (because it must). As @jfriend00 pointed out object property order is never guaranteed in Javascript.

Another point to be made is that you cannot have an object with duplicate keys -- your test object supplied will only have one key when the initialization of the object is finished.

Upvotes: 1

Charlie
Charlie

Reputation: 23848

The order of properties in an object is not guaranteed in Javascript.

Definition of an Object from ECMAScript:

4.3.3 Object

An object is a member of the type Object. It is an unordered collection of properties each of which contains a primitive value, object, or function. A function stored in a property of an object is called a method.

You should either use arrays or map objects which guarantees key order.

Upvotes: 0

Related Questions