3

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.
0

6 Answers 6

3

@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.

2

You need to use the .pop() function on the array to remove the last item.

payees.pop();

Docs: https://docs.soliditylang.org/en/v0.8.12/types.html#array-members

The .length-- approach is invalid since version 0.6.

2

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();
    }
2

You could do it without for-loop

contract RemoveByIndex {
   uint[] public payees = [1, 2, 3, 4, 5];
    function removeByIndex(uint index) public returns(uint[] memory){
        uint lastPayeeIndex=payees.length-1;
        uint lastPayeeId=payees[lastPayeeIndex];
        payees[index]=lastPayeeId;
        payees.pop();
         return payees ;
    }
}

However this would change the order of items. for example, if you wanted to remove index 2, we would bring the last item 5 to seconde index position

 [1, 5, 3, 4, 5]

and then pop the last item

 [1, 5, 3, 4]

If index matters, we could keep track of ids to index in a mapping

contract RemoveByIndex {
   uint[] public payees = [1, 2, 3, 4, 5];
   mapping (uint=>uint) public idToIndex; // {1:0, 2:1}
   // we cannot initialize mapping unlike array, {1:0,2:1,3:2,4:3,5:4}
   // First Call this function
   function populateMapping() public {
        idToIndex[1]=0;
        idToIndex[2]=1;
        idToIndex[3]=2;
        idToIndex[4]=3;
        idToIndex[5]=4;
    }
    // let's we remove index=2
    function removeByIndex(uint index) public returns(uint[] memory){
        uint lastPayeeIndex=payees.length-1;
        uint lastPayeeId=payees[lastPayeeIndex];
        uint idToBeRemoved=payees[index];//
        // we brought the last item to the index that we remove.
        // we end up [1,2,5,4,5]
        payees[index]=lastPayeeId;
        // update the mapping. now in mapping id5 should be 2nd index
        idToIndex[lastPayeeId]=index;// {1:0,2:1,3:2,4:3,5:2}
        delete idToIndex[idToBeRemoved];
        payees.pop();
        return payees ;
    }
}

this looks more complicated but way more gas efficient

2
  • 2
    this is the best suggesstion. I followed the same.. Commented May 20, 2023 at 9:29
  • Avoiding loops should be a MUST approach (except if order matters)
    – AlexAcc
    Commented May 24, 2023 at 7:59
0

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

0

Instruction: For example, there is a structure mapping of length 10 and you only need the details of some users in that mapping, then you take a fixed array inside the method but have imposed the condition that the ID of those users is greater than 0. But maybe if you get some indexing gap then you can do assembly also.

You Can Easily use Solidity Assembly Language Code.

assembly {
    mstore(result, count)
}
struct Task {
    uint id;
    string name;
    address user;
}

// Mapping to store tasks with their unique IDs.
mapping(uint => Task) public tasks;


function viewUserTasks(
    address user
) external view returns (Task[] memory) {
    // Create a memory array to store tasks owned by the specified address.
    Task[] memory result = new Task[](userTasks[user].length);

    // Initialize a counter to keep track of valid tasks for the specified user.
    uint count = 0;

    // Iterate through each task ID in the userTasks array for the specified user.
    for (uint i = 0; i < userTasks[user].length; ) {
        // Get the task ID from the userTasks array.
        uint taskId = userTasks[user][i];

        // Check if the task is owned by the specified address.
        if (tasks[taskId].user == user) {
            // Add a new Task struct to the result array with task details.
            result[count] = Task(
                tasks[taskId].id,
                tasks[taskId].name,
                tasks[taskId].user
            );

            // Increment the counter to move to the next index in the result array.
            unchecked {
                count++;
            }
        }

        // Move to the next task ID in the userTasks array.
        unchecked {
            i++;
        }
    }

    // Resize the array to remove empty slots using inline assembly.
    assembly {
        mstore(result, count)
    }

    // Return the array containing tasks owned by the specified address.
    return result;
}

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.