0

I have been trying to subtract a dictionary value from another in Google Earth Engine but it returns Nan

var dict = ee.Dictionary({
  B1: 182,
  B2: 219,
  B3: 443
});

print(dict.get('B1'));
print(dict.get('B2'));
print(dict.get('B2') - dict.get('B1'));

I don't know why it returns Nan instead of 37 enter image description here

1 Answer 1

2

This fails because the numbers are server-side objects, and you're trying to apply a client-side - operation on them. Read up on server- vs client-side here. To do subtraction with server-side numbers, you do this:

a.subtract(b)

A second issue is that ee.Dictionary.get() returns an ee.Element. You have to cast it to an ee.Number before you use it:

ee.Number(dict.get('B2')).subtract(ee.Number(dict.get('B1')))

Alternatively, you can use ee.Dictionary.getNumber(), to directly get an ee.Number:

dict.getNumber('B2').subtract(dict.getNumber('B1'))

When you have more complex expression, it's often more readable to use ee.Number.expression():

ee.Number.expression('B2 - B1', dict))

Finally, there are times where you actually don't need to use a server-side ee.Dictionary. Just go ahead and use a plain object, if that's the case:

var plainObject = {
  B1: 182,
  B2: 219,
  B3: 443
}
print(plainObject.B2 - plainObject.B1)

https://code.earthengine.google.com/903281ef4bfe0ac52f645f9747f44b56

2

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.