0

Hello i have these smart contracts:

contract CarFactory {

    Car[] deployedCars;
 
    function createCar() public {
       Car newCar=new Car(this);
       deployedCars.push(newCar);  
     }

     function getDeployedCars() public view returns (Car[] memory) {
       return deployedCars;
     }

     function getDeployedCarsWhereTrue() public view returns (Car[] memory) {
       return deployedCars ///where bool made is true;
     }
}


contract Car {

      CarFactory  factory;

       bool made;
    
     constructor(CarFactory  _factory) {
       factory=_factory;
     }

      function makeTrue() {
       made=true;
     }

}

And i need the function getDeployedCarsWhereTrue to return only the addresses where the bool in the smart contract is true.Is that possible?

1 Answer 1

1

You need to check every element inside the array, I added the getCount function to be able to declare a size for the dynamic array:

 function getDeployedCarsWhereTrue() public view returns (Car[] memory) {
   uint count = getCount();
   Car[] memory result =  new Car[](count);;
   for(uint i = 0; i < deployedCars.length; i ++){
     if(deployedCars[i].made){
       result.push(deployedCars[i]);
     }
   }
   return result;
 }

function getCount() internal view returns (uint) {
  uint count;

  for (uint i = 0; i < deployedCars.length; i++) {
    if(deployedCars[i].made){
        count++;
    }
  }

  return count;
}

Neededless to say this is going to be very expensive in gas, I recommend having a separate array to save the made Cars.

1
  • 1
    thanks for your help .Yeah ik that this would be expensive but i wanted to see how it works.thx!
    – zzz
    Jan 19, 2022 at 18:49

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.