0

I am trying to delete an element from an array without knowing its index in the array. Is there a way to delete an element from an array based off of its value not its index?

Something like:

index = array.find(element)

delete array[index]

2 Answers 2

0

There's no implementation of the findByElement of array in Solidity.

But you can achieve this several ways:

  • Write your own function to find element, can be simple as:
function findElementInArray(element, arr) public returns(int) {
    bytes32 encodedElement = keccak256(abi.encode(element.id));
    for (int i = 0 ; i < arr.length; i++) {
        if (encodedElement == keccak256(abi.encode(element.id))) {
            return i;
        }
    }
    return -1;
}
  • Use a mapping to keep the ref from the object into the index of the element in array
mapping(_YourObject -> int) arrayIndexes

// delete object:
delete array(arrayIndexes[object])
0

I got one, you can use it as a library.

library Array {
    function removeElement(uint256[] storage _array, uint256 _element) public {
        for (uint256 i; i<_array.length; i++) {
            if (_array[i] == _element) {
                _array[i] = _array[_array.length - 1];
                _array.pop();
                break;
            }
        }
    }
}

Import this into code, and call it like this: yourArray.removeElement(element)

Works in this way: loop over an array, if the indexed element is there, move that element at the end of the array and remove it with .pop().

Limitations are the size of the array since you have to loop over it and the array must contain only unique elements. I'm not entirely sure, but technically if you remove break it can work for a non-unique array as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.