0

In a array that the values are never repeated. Is there a function/library or something similar that you give the value to remove. And the function the empty space in the array??

function remove(uint _valueToFindAndRemove, uint[] _array)  returns(uint[]) {}
  • 1
    If you don't care about the order of the elements, then you can implement it pretty efficiently, while changing very little in the array. – goodvibration Feb 12 at 11:36
  • Regarding the proposed function, no @goodvibration? – UnexpectedCharacter Feb 12 at 11:48
  • What proposed function? – goodvibration Feb 12 at 12:02
  • The function of the answer – UnexpectedCharacter Feb 12 at 12:02
  • 1
    Well... regarding your question in general. Also, I assume that you want this to be applied on a state-variable, so if I understand correctly, then there's no advantage in passing an array and returning an array (i.e., you may as well work directly on the state-variable array). – goodvibration Feb 12 at 12:06
0
function remove(uint _valueToFindAndRemove, uint[] _array)  returns(uint[]) {

    uint[] storage auxArray;

    for (uint i = 0; i < _array.length; i++){
        if(_array[i] != _valueToFindAndRemove)
            auxArray.push(_array[i]);
    }

    return auxArray;
}

I don´t know if this efficiente to a private chain implementation. But can be a way

0

Yes, this sort of thing can be done but the nested loop answer raises some concerns.

First, the OP is silent on whether we are addressing memory variables or state variables. From the proposed solution, I gather the idea is about processing transient state variables. That should be avoided. It is almost certainly an inappropriate division of labour to use expensive contract execution for this purpose. See this: https://blog.b9lab.com/the-joy-of-minimalism-in-smart-contract-design-2303010c8b09

Most good patterns will work with state variables. To be scalable, the algorithm should complete with the same maximum gas cost at any scale. Unbounded for loops are an anti-pattern. Nested unbounded for loops are like anti-pattern squared. If there is a finite maximum number of elements then it is not "unbounded", but the OP doesn't mention this. https://blog.b9lab.com/getting-loopy-with-solidity-1d51794622ad

You can delete elements from unordered sets with the Mapped Structs with Delete-enabled Index pattern shown here: Are there well-solved and simple storage patterns for Solidity?

Explainer covers why it works the way it does: https://medium.com/robhitchens/solidity-crud-part-1-824ffa69509a

Library compatible with solidity 0.5.x here: https://github.com/rob-Hitchens/UnorderedKeySet

Hope it helps.

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.