Miguel Haba
Miguel Haba

Reputation: 57

Order array by value in NodeJS

I am learning node and now I'm trying to order an array like this:

"lng" : [{
        "ES" : 5,
        "EN" : 3,
        "IT" : 4
    }]

(This is a part of a query result in MongoDB), I need to order the array by the number:

"ES" : 5,
"IT" : 4,      
"EN" : 3

I used sort() but this function orders the array alphabetically by the first parameter, but I need order by the second, I've tried a lot of things but without result.

Thank you for your help!

Upvotes: 3

Views: 8692

Answers (2)

Miguel Haba
Miguel Haba

Reputation: 57

Thank you Nikita, adding the key and value the sort works perfectly, my problem now is make the query to get the results with specific key and value...

I can get the elements by the KEY:

db.users.find({"lng.key" : "ES"})

Or by the VALUE:

db.users.find({"lng.value" : 5})

But not the both at the same query :/

[EDIT]

I have find the solution, $elemMatch:

db.users.find({lng_array : {$elemMatch:{key:"ES", value:5}}}) 

Upvotes: 0

NikitaBaksalyar
NikitaBaksalyar

Reputation: 2514

JavaScript has no ordered objects, so first you should transform your object to an array of this kind:

[
    { key: "ES", value: 5 },
    { key: "EN", value: 3 },
    { key: "IT", value: 4 }
]

And then sort by the value key.

You can easily do it as follows:

// ("mongoDbResult" is the variable with an object you get from MongoDB)
var result = mongoDbResult.lng;

result = Object.keys(result).map(function (key) {
  return { key: key, value: result[key] };
});

And then just sort by the value key:

result.sort(function (a, b) {
  return (a.value < b.value) ? -1 : 1;
});

As a result, you should get a sorted array in the result variable.

Upvotes: 6

Related Questions