1

I want to get rid of the last item of a storage array, and have array.length return the proper value.

Currently I'm using delete to zero it out. However, when I then call array.length, it returns the old length.

I assume I then need to resize the array using array.length = whatever. Is that correct, or is there a better way to do this, maybe something like array.pop?

  • I had the same issue other day I was using an array to counting some decrement of addresses, using delete addresses[0]; and testing it if addresses.length == 0. It took some time to figure out that issue. – Eduardo Pereira Oct 25 '17 at 21:37
3

If you start with an array [A,B,C,D,E,F,G] and you delete "D", then you will have an array [A,B,C,nothing,E,F,G]. It's no shorter than before.

Given that the blockchain is immutable, nothing like an actual "delete" is possible. For example, delete won't prevent accidental disclosure. It's too late because the previous value is part of the immutable history.

Applications often have a need for some sort of logical delete. A common approach is to set a bit isValid in a struct to help differentiate between mapped values that merely default to 0 and actual set values that are explicitly 0. It's also common to maintain a list keys to a mapping so iteration is possible. In the case where a majority of keys will be deleted, then one will want to collect garbage and control the size of the key list.

One approach is to treat the list as "unordered", move the last item in the list to the row to delete, and then decrement the list size by 1. This approach ensures a fixed gas cost for the delete operation at any scale. The intuitive idea of reorganizing the array to "remove" the deleted slot but otherwise maintain the order is prohibitively expensive at scale because it involves SSTORE operations for every row "above" the row to delete.

Explained in more detail, here: https://medium.com/@robhitchens/solidity-crud-part-2-ed8d8b4f74ec

Hope it helps.

-1

Because anything deployed to the blockchain is immutable, you won't realistically be able to change the length of deployed array (as it in exists on the blockchain). You'll have to designate another variable in storage that records the length of items currently in the array, and then decrement/increment as you manipulate the array.

  • Why is this down voted? – Andrey Feb 8 '18 at 4:41

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