Reviewing complexity
So far only one answer has addressed the complexity issue, and is a considerable improvement over your solution. As the existing answers have addressed code style I will stick to the complexity as there is a less complex solution.
Looking both ways!?
Your solution is looking in both direction to find the next peak and thus calculate the volume trapped. You do this for each elevation and thus get a complexity of \$O(n^2)\$ and \$O(1)\$ storage.
One answer's suggestion is to store the max values for quick reference which means you will need to increase the storage to \$O(n)\$ in order to get \$O(n)\$ complexity which is a much better approach.
However the extra storage can be avoided.
Look behind.
To solved in \$O(1)\$ storage and \$O(n)\$ complexity use a two pass method that tracks the peak elevation you have already passed over (look behind rather than look both ways)
One that passes from left to right checking all elevations and a second from right to left checking only to the highest peak found in the first pass.
At most you will pass over each elevation twice, and best case is if the right most elevation is the highest you need only pass over each elevation once.
This avoids the memory overhead and improves performance [1], over the best solution so far suggested, by reducing the iterations to an average of \$n * 1.5\$ rather than \$n * 2\$
[1] Note performance does not mean complexity
Example
- \$O(1)\$ storage, \$O(n)\$ complexity solution
I checked its correctness against your function, (farmed to get a good volume of tests, thus far at half a billion tests on random data the two functions agree)
function floodVolume(elevations) {
var peakIdx, i = 0, peak = 0, volume = 0, total = 0;
const depth = (i, elevation = elevations[i]) => {
if (elevation >= peak) {
peak = elevation;
peakIdx = i;
total += volume;
volume = 0;
} else { volume += peak - elevation }
}
while (i < elevations.length) { depth(i++) }
const MAX_IDX = peakIdx;
volume = peak = 0;
while (i-- >= MAX_IDX) { depth(i) }
return total;
}