1

In Google Earth Engine, I am getting an object obj from an aggregate_histogram call, and print(obj) shows the following:

{
  "115.0": 1,
  "137.0": 1,
  "35.0": 137,
  "42.0": 164
}

I would like to extract the key for which the value is largest, so "42.0" (which should please most everyone as the correct answer to any big question).

How can I proceed?

I know how to do it in pure JavaScript, but here it doesn't look like it works:

print(Object.keys(obj))    // yields "[]"

EDIT: adding more info after the first answer by Kosh.

var obj = loc.aggregate_histogram('relativeOrbitNumber_start')

var o = {
  "115.0": 1,
  "137.0": 1,
  "35.0": 137,
  "42.0": 164
};

print(o)
print(obj)
print(Object.keys(o))
print(Object.keys(obj))

This yields the following:

screenshot

mspices
  • 335
  • 2
  • 11

2 Answers2

1

It seems that it has to do with client- and server-side variables.

So service-side processing steps are required.

Here is something that seems to work:

var o = ee.Dictionary(loc.aggregate_histogram('relativeOrbitNumber_start'))
var okeys = ee.List(o.keys())
var ovals = ee.List(o.values())

var minmax = ee.Dictionary(ovals.reduce(ee.Reducer.minMax()))
var maxval = ee.Number(minmax.get('max'))
var maxind = ovals.indexOf(maxval)
var maxkey = okeys.get(maxind)

print('maxkey:', maxkey)

Unfortunately, this variable then can't be used as input to filterMetadata:

// this yields an empty collection, where maxKey = 42.0:
var sel = loc.filterMetadata('relativeOrbitNumber_start', 'equals', maxKey)

// this yields a non-empty collection:
var sel = loc.filterMetadata('relativeOrbitNumber_start', 'equals', 42.0)

So I first have to get it into the client side by using getInfo, as per this answer.

var ms = maxKey.getInfo()  // local string

var mi = parseInt(ms) // local integer

// this yields a non-empty collection:
var sel = loc.filterMetadata('relativeOrbitNumber_start', 'equals', mi)

This seems like a bug though, why wouldn't filterMetadata be able to accept server-side variables as arguments? Especially since using getInfo() is discouraged in the documentation.

mspices
  • 335
  • 2
  • 11
0

Using reduce:

const o = {
  "115.0": 1,
  "137.0": 1,
  "35.0": 137,
  "42.0": 164
};

const max = Object.keys(o).reduce((m, k) => o[m] > o[k] ? m : k)

console.log(max)
Kosh
  • 16,966
  • 2
  • 19
  • 34