I'm trying to write a function that iterates over an array (backwards), performs some function using the data from each index, then deletes that item from the array.
function loopAndClear(uint256 street) public {
uint[] storage array = streetMap[street];
for (uint i=array.length; i > 0; i--) {
uint itemID = array[i-1];
execute(itemID); // do something with the data
if (accounts[itemID].balance == 0) {
delete array[i-1]; // delete from the array
}
}
}
This deletes the last item in the array, but then replaces it with a 0. How can I delete, shortening the array? My function should be left with an empty array at the end.
Changing to the following fixes this:
function loopAndClear(uint256 street) public {
uint[] storage array = streetMap[street];
for (uint i=array.length; i > 0; i--) {
uint itemID = array[i-1];
execute(itemID); // do something with the data
if (accounts[itemID].balance == 0) {
delete streetMap[i-1]; // delete from the array
}
}
}
Kind of interesting. My code from the question still changes the original array, but fills it with 0's instead of deleting. I changed it to the above since I figured the variable assignment on line 2 was just passing the value instead of reference. But on second thought, if that were the case, the original array would go unmodified. Would love to know what's going on here if anyone can point it out :)