Order array by value in NodeJS
arrays, node.js, sorting
Solution
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.
Problem
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!