Having a difficult time with loops and arrays in Solidity. If i have a simple contract like below (no mapping, just a struct array), is it possible to loop through the array to get a particular EntityStruct? Anyone care to show me what this might look like as far as setting up the loop is concerned?

contract simpleList {
     struct EntityStruct {
        address entityAddress;
        uint entityData;
     EntityStruct[] public entityStructs;

You can use a simple for loop. Like this:

function test() public view {
     for (uint i; i < entityStructs.length; i++) {
         address firstAddr = entityStructs[i].entityAddress;

You can manipulate the values inside the loop as you want.

  • Thank you for the response. One question though... does this function have to take address as an argument/input? Where do i input the address I want to look up in the array?
    – Blockpain
    Sep 22 at 22:04
  • No it doesn't have to. It depends on what you need. If you want to find a specific address from the array, then you probably want to take the address as an argument, and compare it against the addresses inside the loop. Something like if (paramAddr == entityStructs[i].entityAddress) { doSomething } Sep 23 at 4:38

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.