3

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!

5
  • are you using mongoose? or mongodb native? please post your full query Commented Feb 20, 2015 at 10:59
  • Are you trying to sort the {"ES":5,"EN":3,"IT":4} JavaScript Object? If I remember correctly, JavaScript objects' key-value pairs don't have an "order". Commented Feb 20, 2015 at 11:04
  • Hi Alex, thanks for reply, I am using Mongoose. Each element of the collection is like that: { "_id" : ObjectId("54a15e7e3453b5741a6c7be0"), "name" : "Miguel", "lng" : { "ES" : 5, "EN" : 3, "IT" : 4 }, "email" : "[email protected]", "password" : "123123" } ...etc. And the query: db.users.find({ "lng.en" : {$lt : 5 } }) I want to get the users who have "EN" with level 1,2,3 or 4. Thank you Commented Feb 20, 2015 at 11:05
  • don't paste code in comments, update your question, and format the code please Commented Feb 20, 2015 at 11:11
  • Sorry Alex, I will do correctly the next time Commented Feb 20, 2015 at 11:52

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.