If I have a random number from 1 ~ 100.
by using the Solidity keyword 'view' and returning a fixed-length array, you can set the length of the memory's array to 100 whenever the random is that's fine.
in order to save gas how to shrink the array and return it.
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
//I have a party, the numbers of people is always uncertainly every time.
contract UncertainlyParty {
struct People {
string id;
string name;
}
uint256 partySize =10 // max people in the party
function getUncertainlyPartyPeopleCount()
external
view
returns (People[] memory)
{
People[] memory people = new People[](partysize); //assume every one is present
for (uint256 i = 0; i < array.partysize; i++) {
people[i] = willParticipateParty();
}
return people; // 🤣🤣 how to return useful data without empty data....
// sometimes 7 people is present, sometings 5 is present.
// it should not be return a people[] array with length 10 & with some empty people records.
// how to declare the array size in dynamic way?
}
function willParticipateParty() public returns(People memory) {
People[] memory people = new People[](1);
// fake code, to get random number
if(block.timestamp % 2 ==0){ I will be present.(with data.)
people.id= 'increasing..';
people.name = 'bula bula';
return people;
}else{
return people; // I will not be present (no data useless data)
}
}
}
Ok, it's a good question. One way to do this is to first allocate the array with length partysize, then don't assign to each of the people[i] elements, but push the number i to the array. At the end you can reset the array length to the total that you found will attend. The operation .push is not available for arrays in memory so you have to maintain an index manually, and resetting the array length I don't think is supported natively so you may need to use assembly.
You must keep in mind that even if you return the smaller array, you will still be allocating enough memory for the larger array, and this can have an effect in your gas costs.
As usual, it's generally not a good idea to manipulate arbitrary-length arrays in the EVM, but if you have a reasonable upper bound it's ok.
Thank you for your Good answer. in order to use Valid Array Data in Front-end and reduce error.
I declared an new array and filter it. Finnaly we have a Valid Array Data