1

I am writing a function that iterates over a list of numbers in GEE, and I would like to count which iteration the function is currently in since I need it to run other calculations. However, I haven't found the way of doing so. Trying the classical approach (i.e. j=j+1) returns a false result. The code example is below:

var j = ee.Number(0);

var test = ee.List([10,42,5,1,78,6]).iterate(function(i,list){
  j = ee.Number(j.add(1))
  var accum = ee.Number(i).add(ee.List(list).get(-1))
  return ee.List(list).add(accum)
},ee.List([0]));

print(test);
print(j);

The code print the final j as 3 when there clearly are 6 elements in the list.

2 Answers 2

0

You can't modify global variables in an iterated or mapped function.

The simpler way is to iterate over the indexes, not the list.

list = ee.List([10,42,5,1,78,6])
test = ee.List.sequence(0, list.size()).iterate(function(index, result) {
    ...
})

That said, it's generally better to avoid iterate() if possible, since it doesn't scale well.

0

Figured it out, it's a bit convoluted but I think there is no other way, the way of getting the current iteration is (in this case) ee.List([10,42,5,1,78,6]).indexOf(i)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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