how to delete item of array in solidity

Viewed 2486

I am trying to remove a certain item of the array in solidity.
I was exploring some articles.
https://ethereum.stackexchange.com/questions/1527/how-to-delete-an-element-at-a-certain-index-in-an-array

Of course, I don't need the empty value of the item. I need to remove completely the item.

uint[] payees = [1, 2, 3, 4, 5];

delete payees[0]

// result - I don't need this result

[0, 2, 3, 4, 5]

//I need [2, 3, 4, 5]

So I have used this function.

function removePayee(
        uint256 index
    ) internal {
        if (index >= payees.length) return;

        for (uint i = index; i<payees.length-1; i++){
            payees[i] = payees[i+1];
        }
        delete payees[payees.length-1];
        payees.length--;
    }

The following error has occurred.

Member "length" is read-only and cannot be used to resize arrays.

Please help me.

4 Answers

@Petr Hejda has already given the answer. You just need to remove last two lines of code and add "pop()" instead.

    uint[] payees = [1, 2, 3, 4, 5];

    function removePayee(uint256 index) external {
        if (index >= payees.length) return;

        for (uint i = index; i<payees.length-1; i++){
            payees[i] = payees[i+1];
        }
        payees.pop();
    }

Also, optional: instead of "if statement" there I would use "require". But this won't affect the code for now.

As I know after solidity 0.6.0 no one uses payees.length-- anymore for replacing that zero value exposes of delete keyword we should replace elements one index back after index chooses at function input.

So You should use payees.pop() instead of payees.lenght--

There could be two approaches:

If you want to preserve order:

function removePayee(
        uint256 index
    ) internal {
        if (index >= payees.length) return;

        for (uint i = index; i < payees.length - 1; i++) {
           payees[i] = payees[i+1];
        }
        payees.pop();
    }

If you don't care about preserving order:

function removePayee(
        uint256 index
    ) internal {
        if (index >= payees.length) return;

        payees[index] = payees[payees.length - 1];
        payees.pop();
    }
Related