0

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 :)

1 Answer 1

0

you should use array.pop(), that way the length will be -- at each iteration, delete on the other hand just reset the element to the default value.

under the hood, pop also calls delete, so you will be getting the gas refund you'd get from calling delete.

2
  • array.pop only deletes the last position of the array. It doesn't shift the array if you want to delete an index in the middle of the array.
    – Ismael
    Jun 4, 2023 at 5:39
  • good note for people wanting to delete an item in the middle of an array, the question specified that the array should be empty after finishing the loop though
    – Ahmad Atef
    Jun 6, 2023 at 7:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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