Home > Software design >  How To reverse an array in Solidity?
How To reverse an array in Solidity?

Time:07-19

Create a function reverseArray(array, length of array) . This reverseArray() will take two arguments - a dynamic uint type array and length of the array. The reverseArray() will reverse the array. For Example - If array =[2,5,9,11,1] then reverseArray() will return [1,11,9,5,2] If array =[90,20,30,10] then reverseArray() will return [10,30,20,90]

CodePudding user response:

should be like that

for (uint i = a.length; i > 0; i--) {
    emit ReverseLoop(a[i-1]);
}

CodePudding user response:

Here you go!

function reverseArray(uint[] calldata _array) public pure returns(uint[] memory) {
    uint length = _array.length;
    uint[] memory reversedArray = new uint[](length);
    uint j = 0;
    for(uint i = length; i >= 1; i--) {
        reversedArray[j] = _array[i-1];
        j  ;
    }
    return reversedArray;
}
  • Related