0

I have a struct array like so:

struct People {
        uint256 age;
        string name;
}

People[] public peopleArray;

Is there a way I can easily get an array containing the ages of the People? The code I have now is something like:

function getPeopleAges() public view returns (uint256[] memory) {
        uint256[] memory temp = new uint256[](peopleArray.length);
        for (uint8 i = 0; i < peopleArray.length; i++) {
            temp[i] = peopleArray[i].age;
        }

        return temp;
    
}

This seems needlessly bulky, so I was wondering if there was a more simplified or better way to do this. For example, in javascript you can do something like this:

return peopleArray.map(a => a.age);

Is there a solidity equivalent to that?

2 Answers 2

0

I think a loop would be the only way to do it that way, hoewever you could just add the age to the peopleArray in the same function you add the age and name to the People struct.

2
  • I thought about that, but I was concerned about the extra storage of always carrying that redundant info.
    – l1nkm4rine
    Commented Nov 29, 2022 at 16:21
  • What is the use case for this array? there may be a better option. Commented Nov 29, 2022 at 16:24
0

The EVM is constrained by hard limits on execution cost. Consequently, you want to optimize thr storage layout precisely to avoid convoluted conversions like that.

You could have two arrays, one for ages and one for names, and that would get you some of the way there, but I would caution you about scalability. What happens when the arrays get large?

Scalability depends on always having an O(1) solution. Some food for thought: https://blog.b9lab.com/getting-loopy-with-solidity-1d51794622ad

Hope it helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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