Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to order a dictionary by value in AngularJS

I've a REST api that returns the list of locales as dictionary:

{
"en-uk": "English UK",
"en-us": "English USA",
...
}

This dictionary is correctly ordered alphabetically by value.

When AngularJS receives it via HTTP, the dictionary gets automatically re-sorted by key, so when I bind to a select element the list of options is ordered by key, and the alphabetical order by key doesn't match the one by value, I get a wrong sorting.

The problem I suppose is due to the fact that such dictionary becomes basically one object with 800+ properties. How do I sort it by value?

like image 534
CodeClimber Avatar asked Jan 18 '26 15:01

CodeClimber


1 Answers

First: You have to find all keys.

Second: Iterate all the keys.

Third: Then sort the array with values.

Please use the following:

let obj = {
"en-us": "English USA",
"en-uk": "English UK"
};

// Get an array of the keys:
let keys = Object.keys(obj);

// Then sort by using the keys to lookup the values in the original object:
keys.sort(function(a, b) { return obj[a] > obj[b] });

console.log(keys);
console.log(obj[keys[0]]);
like image 119
I. Ahmed Avatar answered Jan 21 '26 06:01

I. Ahmed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!