You can do this with some array image fiddling. That's always a bit tricky, and not very easy on the eyes. To understand this, I suggest that you add the intermediate array images to the map and inspect, to see what they contain.
var anomYearArray = anom
.toArray() // Convert collection to 2D array image
var anomArray = anomYearArray.arraySlice(1, 0, 1)
var anomYearSorted = anomYearArray
.arraySort(anomArray) // Sort by anomaly
var rankArray = anomArray.not().not() // An array of 1
.arrayAccum(0, ee.Reducer.sum()) // An array from 1 to number of anomalies
.multiply(-1).add(anomArray.arrayLength(0)).add(1) // Reverse array
var anomYearRankArray = anomYearSorted.arrayCat(rankArray, 1)
var rankedAnom = ee.ImageCollection(
ee.List.sequence(startYear, endYear)
.map(function (year) {
year = ee.Number(year)
var yearMask = anomYearRankArray.arraySlice(1, 1, 2).eq(year)
var yearImage = anomYearRankArray.arrayMask(yearMask)
.arrayProject([1])
.arrayFlatten([['anom', 'year', 'rank']])
.set('year', year)
.set('system:time_start', ee.Date.fromYMD(year, 1, 1))
return yearImage
})
)
var anom2020 = rankedAnom.filterMetadata('year', 'equals', 2020)
Map.addLayer(anom2020, {bands: 'rank', min: 1, max: endYear - startYear + 1}, 'rank 2020')
https://code.earthengine.google.com/82c841c8936fc562f6b17760876a9730
Here it is plugged into your complete script: https://code.earthengine.google.com/96066c8aea034d99bf4393eba8bf51f5