It's usually a good idea to avoid getInfo()
calls. It locks up the page, and slow down your execution. Below are a couple of different implementations. They're not very simple, but avoid getInfo()
calls.
You have to decide how to deal with cases where the value you search for isn't present. You might want to return something, give an error, or you simply know it cannot happen and happily ignore it.
https://code.earthengine.google.com/21a7c7b22138541b424b00489128f74c
var list = ee.List([
[101, 12155],
[102, 12157],
[103, 12158]
])
print(
'findWithIf',
findWithIf(list, 102),
findWithIf(list, 104)
)
print(
'findByIndex',
findByIndex(list, 102),
findByIndex(list, 104)
)
print(
'findMaskingArray',
findMaskingArray(list, 102),
findMaskingArray(list, 104)
)
print(
'findUsingDictionary',
findUsingDictionary(list, 102),
findUsingDictionary(list, 104)
)
function findWithIf(list2D, value) {
return list2D
.map(function (tuple) {
tuple = ee.List(tuple)
return ee.Algorithms.If(
tuple.getNumber(0).eq(value),
tuple.getNumber(1),
null
)
}, true)
.cat([null]) // Not found returns null
.getNumber(0)
}
function findByIndex(list2D, value) {
var array = ee.Array(list)
var keys = array.slice(1, 0, 1).project([0]).toList()
var values = array.slice(1, 1, 2).project([0]).toList()
var index = keys.indexOf(value)
return values
.cat([null]) // Not found returns null
.getNumber(index)
}
function findMaskingArray(list2D, value) {
var array = ee.Array(list)
var keys = array.slice(1, 0, 1).project([0])
var values = array.slice(1, 1, 2).project([0])
var mask = ee.Array(ee.List.repeat(value, keys.length().get([0])))
return values
.mask(keys.eq(mask))
.toList()
.cat([null]) // Not found returns null
.getNumber(0)
}
function findUsingDictionary(list2D, value) {
var array = ee.Array(list)
var keys = array.slice(1, 0, 1).project([0]).toList()
.map(function (key) { // Turning keys into strings
return ee.Number(key).format()
})
var values = array.slice(1, 1, 2).project([0]).toList()
return ee.Number(
ee.Dictionary.fromLists(keys, values)
.get(ee.Number(value).format(), -1) // Not found returns -1
)
}