[Ethereum] How to delete array at index

solidity

How do you delete an array at a certain index in solidity? I'm trying to access the index via key and not the index number.

function deleteAtIndex(address _address) {
    delete sellers[_address];
}

The error I'm receiving is
TypeError: Type address is not implicitly convertible to expected type uint256. I also know that deleting this will leave a 0 at the index. Is there any way around this without shifting the entire array since I know it's expensive?

Best Answer

You're getting that problem because you're trying to search through the indexes of the array using an address which is not valid, you must search using uints. You can however use a pattern to make the index of the address easily retrievable.

Here's a pattern I use to do just this

address[]   public sellers;
mapping (address => uint256) public arrayIndexes;
function addAddress(address _addr) public {
    uint id = sellers.length;
    arrayIndexes[_addr] = id;
    sellers.push(_addr);
}

function removeAddress(address _addr) public {
    uint id = arrayIndexes[_addr];
    delete sellers[id];
}

One thing to note is that this doesn't preserve order in the array, and whatever address you delete will turn into the nu;l address 0x0000000000000000000000000000000000000000

Related Topic