Google Earth Engine – How to Sort Dictionary Values and Get Sorted Keys in a New Dictionary

dictionarygoogle-earth-enginegoogle-earth-engine-javascript-apisortingvalues

How can I sort a dictionary's keys in Earth Engine based on their values?

For example, I have such a dictionary defined in Earth Engine after some calculations and I want to sort that based on dictionary values and get sorted new dictionary based on sorted keys and values.

Here is a simple example for that :

var MyDic=ee.Dictionary({
  A: 2.318244235030834,
  B: 8.901825525058984,
  C: 6.9262150730973815,
  D: 1.1614314188052866
})
print('MyDic',MyDic)
var Sorted=ee.Dictionary(MyDic).values().sort()

print('Sorted',Sorted)

var sorted_new_keys = Sorted.map(function(ele) {
  
  return MyDic.get(ele);
  
});

print('sorted_new_keys',sorted_new_keys)
//

So I could see the values as (8.90, 6.93 and so on).

When I run the above code I receive the following results:

Sorted
List (4 elements)
0: 1.1614314188052866
1: 2.318244235030834
2: 6.9262150730973815
3: 8.901825525058984

I want to get true keys as A, B, … not 0, 1, …

My full code is at https://code.earthengine.google.com/b42a11a87457daef9eb9b8b256f461c2

Best Answer

Because dictionaries by design do not have an order, you can't really sort a dictionary itself, only the keys or the values. If you want the order of the keys, based on some sort of other values, you could simply use the keys argument of ee.List.sort().

var dict = ee.Dictionary({
  A: 2.318244235030834,
  B: 8.901825525058984,
  C: 6.9262150730973815,
  D: 1.1614314188052866
})

var sorted_keys = dict.keys().sort(dict.values())

This sorts the keys of the dictionary based on the order of the values. But since dictionaries do not have an intrinsic order, you have to save everything as a List, or as list of lists.

var sorted = ee.List([sorted_keys, dict.values().sort()])
print(sorted)

Another option would be to save the keys and values as seperate properties in a feature collection and sort that.

var dict_to_fc = ee.FeatureCollection(dict.keys().map(function(k){
  return ee.Feature(null, {key: k, value: dict.getNumber(k)})
}))

var sorted = dict_to_fc.sort('value')
print(sorted)
Related Question