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]
Ethereum Stack Exchange is a question and answer site for users of Ethereum, the decentralized application platform and smart contract enabled blockchain. It only takes a minute to sign up.
Sign up to join this communityThere's no implementation of the findByElement of array in Solidity.
But you can achieve this several ways:
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;
}
mapping(_YourObject -> int) arrayIndexes
// delete object:
delete array(arrayIndexes[object])
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, overwrite the searched element with the last element and .pop()
the last item of the array.
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.