0

How can I say for each unique address of an array do something?

I'm calling a function which adds an address to an array every time it is called. I would preferably not want to add another identical address to the same array if it already exists within, is this possible to check for?


else, how can I work around this when calling functions that loops through the particular array? because it basically applies the action to the same address x amount of times that it is present in the array per function call.

1

I would preferably not want to add another identical address to the same array if it already exists within, is this possible to check for?

Define an additional mapping and use it to check whether you've already added the address to the array:

mapping (address => bool) isAdded;

Set to true when you first add the address to the array:

isAdded[<address>] = true;
1

As a general-purpose tool, this sounds to me like an enumerable set. I've written a blog post about how to build this: https://programtheblockchain.com/posts/2018/06/03/storage-patterns-set/.

This code goes beyond what you're asking for, because it also supports removal:

pragma solidity ^0.4.24;

contract Set {
    bytes32[] public items;

    // 1-based indexing into the array. 0 represents non-existence.
    mapping(bytes32 => uint256) indexOf;

    function add(bytes32 value) public {
        if (indexOf[value] == 0) {
            items.push(value);
            indexOf[value] = items.length;
        }
    }

    function remove(bytes32 value) public {
        uint256 index = indexOf[value];

        require(index > 0);

        // move the last item into the index being vacated
        bytes32 lastValue = items[items.length - 1];
        items[index - 1] = lastValue;  // adjust for 1-based indexing
        indexOf[lastValue] = index;

        items.length -= 1;
        indexOf[value] = 0;
    }

    function contains(bytes32 value) public view returns (bool) {
        return indexOf[value] > 0;
    }

    function count() public view returns (uint256) {
        return items.length;
    }
}

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.