[Ethereum] How to delete an element at a certain index in an array

contract-developmentsolidity

Anyone know how to delete an element in a array? Is there any built in method to do that?

If not, does anyone know of how to implement such a method?

Best Answer

Use the delete operator to delete the element:

delete array[index];

If you don't want to leave a gap, you need to move each element manually:

contract test{
    uint[] array = [1,2,3,4,5];
    function remove(uint index)  returns(uint[]) {
        if (index >= array.length) return;

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

If you don't care about the order, you can also just copy the last element into the empty spot, then delete the last element.

Related Topic