简体   繁体   中英

find and remove element from array (solidity)

I've tackled a task: find a specific address in a sheet, move it to the end of the sheet, and remove it via a function pop: here is the code:

function removeAccount(address _account) external{
        uint counter = arrayOfAccounts.length;
        uint index;
        for(uint i; i < counter; i++) {
            if(arrayOfAccounts[i] == _account){
                index = i;
                break;
            }
        for(uint i = index; i < counter-1; i++){
                arrayOfAccounts[i] = arrayOfAccounts[i + 1];
            }
            arrayOfAccounts.pop();
        }
    }
        }
    }

transact to Wote.removeAccount errored: VM error: revert.

revert The transaction has been reverted to the initial state. Note: The called function should be payable if you send value and the value you send should be less than your current balance. Debug the transaction to get more information.

In case you dont care about addresses order

function removeAccount(address _account) external {
    if(arrayOfAccounts.length == 1) {
        arrayOfAccounts.pop();
    }
    else if(arrayOfAccounts[arrayOfAccounts.length - 1] == _account) {
        arrayOfAccounts.pop();
    }
    else {
        for (uint i = 0; i < arrayOfAccounts.length - 1; i++) {
            if(_account == arrayOfAccounts[i]) {
                arrayOfAccounts[i] = arrayOfAccounts[arrayOfAccounts.length - 1];
                arrayOfAccounts.pop();
            }
        }
        
    }
}

If order matters

function removeAccount(address _account) external{
        uint counter = arrayOfAccounts.length;
        for(uint i; i < counter; i++) {
            if(arrayOfAccounts[i] == _account){
                for(uint j = i; j < counter-1; j++){
                    arrayOfAccounts[j] = arrayOfAccounts[j + 1];
                }
                arrayOfAccounts.pop();
                break;
            }
        }
    }
}

Else if order doesn't matter

function removeAccount(address _account) external{
    uint numAccounts = arrayOfAccounts.length;
    for(uint i = 0; i < numAccounts; i++) {
        if(arrayOfAccounts[i] == _account){    // if _account is in the array
            arrayOfAccounts[i] = arrayOfAccounts[numAccounts - 1];    // move the last account to _account's index
            arrayOfAccounts.pop();    // remove the last account
            break;
        }
    }
}

The reason is just simple. You used the second for loop inside the first for loop. And also please initialize the index with counter ;

uint256 index = counter;

And pop only when index is less than counter

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM